flutter check if json list has data
- User
flutter check if json list has data
- Assistant
If you have a JSON list (a list decoded from a JSON string) in Flutter/Dart and you want to check if it has any data, you typically want to verify that the list is not null and not empty.
Here's a simple example:
import 'dart:convert'; void main() { String jsonString = '[{"id":1,"name":"John"},{"id":2,"name":"Jane"}]'; // Decode JSON string to dynamic object var decoded = jsonDecode(jsonString); // Check if decoded is a List and if it has data if (decoded is List && decoded.isNotEmpty) { print('List has data'); } else { print('List is empty or not a list'); } }Explanation:
jsonDecodeconverts a JSON string into a Dart object (usually Map or List depending on JSON).- You check if the decoded data is a
Listusingis List. - Then check
decoded.isNotEmptyto ensure it contains elements.
In a function context
If you get JSON from an API:
void processJsonData(String jsonString) { final data = jsonDecode(jsonString); if (data is List && data.isNotEmpty) { // Do something with the list data } else { // Handle empty list or invalid data } }
Summary:
To check if a JSON list has data in Flutter/Dart:
- Decode the JSON string using
jsonDecode - Verify it's a List with
is List - Confirm it’s not empty with
isNotEmptyflag
Let me know if you want example with actual API call or different structure!
- User
check if value is not null else load widget in body
- Assistant
If you want to check if a value (e.g. data from JSON, an API, or any variable) is not null, and conditionally display a widget based on that in your Flutter widget's body, you can use a simple ternary operator or an
ifcondition inside thebuildmethod.Basic example:
class MyWidget extends StatelessWidget { final dynamic data; // This could be any data (String, List, Map, etc.) MyWidget({this.data}); @override Widget build(BuildContext context) { return Scaffold( body: data != null ? Center(child: Text('Data is: $data')) : Center(child: CircularProgressIndicator()), ); } }Explanation:
- If
datais not null, it shows the data inside aTextwidget. - Otherwise, it shows a
CircularProgressIndicator(can be any widget you want — loading spinner, message, placeholder, etc.).
Example with JSON list check and widget:
import 'dart:convert'; import 'package:flutter/material.dart'; class MyJsonListWidget extends StatelessWidget { final String jsonString; MyJsonListWidget({required this.jsonString}); @override Widget build(BuildContext context) { final decoded = jsonDecode(jsonString); // Check if decoded is a non-empty List final hasData = decoded is List && decoded.isNotEmpty; return Scaffold( body: hasData ? ListView.builder( itemCount: decoded.length, itemBuilder: (context, index) { return ListTile( title: Text(decoded[index]['name']), ); }) : Center( child: Text('No data available'), ), ); } }Summary:
- Check if value is
null - If not null, show the normal widget and data
- Else, show a placeholder/loading widget in the
body
If you want, I can also help with a
FutureBuilderexample if you’re fetching data asynchronously. Just ask! - If
- User
CircularProgressIndicator make app blinking or show some random shape on screen
- Assistant
If
CircularProgressIndicatorcauses your Flutter app to blink or show weird/random shapes, this usually points to a problem with the widget tree being rebuilt rapidly or the indicator used improperly.Here are some common causes and solutions:
1. Rapid rebuilds causing blinking or flashing
If your widget is rebuilding too fast (e.g., in every frame or state change), the CircularProgressIndicator can appear to blink.
Solution:
Make sure you are not callingsetStateor rebuilding your widget unnecessarily.
2. Missing Scaffold or MaterialApp
CircularProgressIndicatordepends on Material widgets for styling. If it's not wrapped inside aMaterialAppandScaffoldor other Material widgets, it can paint incorrectly.Make sure your app has this basic structure:
MaterialApp( home: Scaffold( body: Center(child: CircularProgressIndicator()), ), );
3. Not using
Centeror size constraintsIf you put
CircularProgressIndicatordirectly into a place without constraints (like directly in aColumnorRowwithout expanding it or centering it), it can cause layout issues.Always wrap it in a
Centeror give it size constraints:Center( child: CircularProgressIndicator(), )
4. Multiple overlapping indicators
Make sure you don't have multiple progress indicators stacked on top of each other accidentally, which can cause flickering or odd rendering shapes.
5. Example of correct usage
import 'package:flutter/material.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: Text('Progress Indicator Example')), body: Center( child: CircularProgressIndicator(), ), ), ); } }
6. If your progress indicator is inside a stateful widget and conditionally shown
Example:
class MyLoadingWidget extends StatefulWidget { @override _MyLoadingWidgetState createState() => _MyLoadingWidgetState(); } class _MyLoadingWidgetState extends State<MyLoadingWidget> { bool isLoading = true; @override void initState() { super.initState(); // Simulate loading delay to change state after some time Future.delayed(Duration(seconds: 3), () { setState(() { isLoading = false; }); }); } @override Widget build(BuildContext context) { return Scaffold( body: Center( child: isLoading ? CircularProgressIndicator() : Text('Loaded!'), ), ); } }This will show the loader for 3 seconds, then display the text.
Summary checklist:
- Wrap
CircularProgressIndicatorinsideCenter - Use
MaterialAppandScaffold - Avoid rapid rebuilds (check your logic if
setStateor streams cause re-rendering too often) - Make sure no overlapping widgets interfere
- Test minimal example to isolate the issue
If you can share code snippet where you use the indicator, I can help debug further!
- Wrap
- User
CircularProgressIndicator altrinative
- Assistant
If you're looking for alternatives to
CircularProgressIndicatorin Flutter—either because of the blinking/weird appearance issue or you want a different style/loading indicator—here are some options you can consider:
1. LinearProgressIndicator
A Material-style horizontal progress bar:
Center( child: LinearProgressIndicator(), )
2. Third-party loading indicators
There are great Flutter packages with customizable and fancy loading animations:
flutter_spinkit
dependencies: flutter_spinkit: ^5.1.0Usage example:
import 'package:flutter_spinkit/flutter_spinkit.dart'; Center( child: SpinKitFadingCircle( color: Colors.blue, size: 50.0, ), )Popular spin kit widgets:
SpinKitFadingCircleSpinKitChasingDotsSpinKitCircleSpinKitCubeGridSpinKitWave- Many more...
3. Custom Animated Widgets
You can create your own animation with
AnimatedBuilderorAnimatedWidgetfor fully custom loaders.Example (simple pulsating dot):
class PulsatingDot extends StatefulWidget { @override _PulsatingDotState createState() => _PulsatingDotState(); } class _PulsatingDotState extends State<PulsatingDot> with SingleTickerProviderStateMixin { late AnimationController _controller; late Animation<double> _animation; @override void initState() { super.initState(); _controller = AnimationController(vsync: this, duration: Duration(seconds: 1)) ..repeat(reverse: true); _animation = Tween<double>(begin: 0.5, end: 1.0).animate(_controller); } @override void dispose() { _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return ScaleTransition( scale: _animation, child: Container( width: 20, height: 20, decoration: BoxDecoration(color: Colors.blue, shape: BoxShape.circle), ), ); } }Use inside your UI:
Center(child: PulsatingDot())
4. Using a static image or GIF
Sometimes, you can use a custom loading gif or Lottie animation:
- Use lottie for beautiful json animations.
- Or use
Image.assetwith a gif file.
Example using Lottie:
dependencies: lottie: ^2.2.0import 'package:lottie/lottie.dart'; Center( child: Lottie.asset('assets/loading_animation.json'), )
5. Use
RefreshProgressIndicator(Material)This is a circular progress indicator with a slightly different style used in pull-to-refresh widgets:
Center( child: RefreshProgressIndicator(), )
Summary
Alternative Description Package LinearProgressIndicatorHorizontal progress bar Flutter SDK flutter_spinkitLots of customizable spinners pub.dev/flutter_spinkit Custom Animated Widget Full control & custom animations - Lottie Animations JSON-based vector animations pub.dev/lottie RefreshProgressIndicatorCircular indicator styled for refresh controls Flutter SDK
If your original problem was related to blinking or weird UI with CircularProgressIndicator, I recommend first verifying your widget tree, and if issue persists, try
flutter_spinkitwhich is widely used and very stable.
Let me know if you want example code from any of these alternatives!
- User
why app not stable when animation is happen in it like RefreshProgressIndicator or changing color button how to fix it if it blink etc
- Assistant
When your Flutter app becomes unstable, blinks, flickers, or shows weird artifacts during animations like
RefreshProgressIndicatoror a button whose color changes, it’s usually due to how the widget tree is rebuilt or inefficient animation management.Here’s why this might happen and how to fix it:
Why blinking or flickering happens during animations:
1. Excessive or unnecessary rebuilds
- If your widget (or whole screen) is rebuilding too often (e.g., on every frame unnecessarily), animations may appear to blink or flicker.
- This happens if you call
setStatein places that trigger rebuilds unrelated to the animation, or call it redundantly inside animation listeners.
2. Improper use of animations
- Using animations but recreating animation controllers or animations inside
build()instead ofinitState()causes controllers to be recreated every build. - This resets animations repeatedly and creates visible flickering.
3. Widgets losing their identity
- If widgets that should be stable during animation are rebuilt with different keys or replaced with different types, Flutter will rebuild the subtree completely causing flicker.
- E.g., rebuilding entire lists or components unnecessarily instead of updating their state carefully.
4. No explicit size or layout constraints
- If animated widgets are inside layout structures that can resize or reposition during animation (e.g., changing button colors causes re-layout), this can cause visual jumps or flickering.
How to fix blinking & improve animation stability:
1. Use
StatefulWidgetand manage animations properly- Create
AnimationControllerand animations only once insideinitState, dispose of them indispose. - Do NOT create them inside
build().
Example:
class MyAnimatedButton extends StatefulWidget { @override _MyAnimatedButtonState createState() => _MyAnimatedButtonState(); } class _MyAnimatedButtonState extends State<MyAnimatedButton> with SingleTickerProviderStateMixin { late AnimationController _controller; late Animation<Color?> _colorAnimation; @override void initState() { super.initState(); _controller = AnimationController( duration: Duration(seconds: 1), vsync: this, ); _colorAnimation = ColorTween(begin: Colors.blue, end: Colors.red).animate(_controller); // Optionally repeat/forward animation _controller.repeat(reverse: true); } @override void dispose() { _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return AnimatedBuilder( animation: _colorAnimation, builder: (context, child) { return ElevatedButton( style: ElevatedButton.styleFrom( primary: _colorAnimation.value, ), onPressed: () {}, child: Text('Animated Color Button'), ); }, ); } }2. Avoid calling
setStateunnecessarily- Only call
setStatewhen you really need to update UI. - Inside animation listeners, consider using
AnimatedBuilderorAnimatedWidgetinstead to implicitly listen to changes without manualsetState.
3. Use widgets designed for animation
- Use widgets like
AnimatedContainer,AnimatedOpacity,AnimatedCrossFade,AnimatedSwitcher, etc., which handle animations efficiently and minimize rebuild issues.
4. Keep animations and state scoped
- Avoid rebuilding entire screens/widgets during animation. Isolate animations into smaller widgets to prevent large rebuilds.
5. Fix layout jitter
- To avoid flickering due to size/position changes during animation, keep widget sizes fixed or use constraints.
- For example, wrap the animated widget in a
SizedBoxorContainerwith fixed width and height.
6. Example of a stable RefreshProgressIndicator usage
class MyLoadingScreen extends StatefulWidget { @override _MyLoadingScreenState createState() => _MyLoadingScreenState(); } class _MyLoadingScreenState extends State<MyLoadingScreen> { bool isLoading = true; @override void initState() { super.initState(); // Simulate loading delay Future.delayed(Duration(seconds: 3), () { setState(() { isLoading = false; }); }); } @override Widget build(BuildContext context) { return Scaffold( body: Center( child: isLoading ? RefreshProgressIndicator() : Text('Loaded!'), ), ); } }If in your real app it flickers, check that you aren't rebuilding the whole tree or widget unnecessarily or switching widgets with different layouts.
Summary / Checklist
- ⏰ Initialize animations in
initStateand dispose indispose - ❌ Don’t recreate controllers or animations inside
build() - 🗝 Use keys properly, avoid unnecessary widget replacement
- 📦 Minimize rebuild scope of animations — isolate animated parts in small widgets
- 🔄 Use
AnimatedBuilder,AnimatedWidgetor Flutter built-in implicit animations (AnimatedContainer) instead of manualsetStateon each frame - 📏 Fix layout size and constraints during animation
- 🤔 Profile widget rebuilds with Flutter DevTools to find frequent rebuilds
If you want, share your specific widget/code and I can help debug why your animation causes blinking in your app!
- User
other suliution
- Assistant
If the typical fixes for animation flickering or blinking in Flutter don’t work or you want a different approach, here are some additional solutions and architectural tips that can help you achieve smooth, stable animations and avoid blinking issues:
Alternative Approaches to Fix Animation Flicker or Instability
1. Use
ValueListenableBuilderorStreamBuilderInstead of
setStatedriven animation or state changes,ValueNotifierandValueListenableBuilderdecouple state updates from full widget rebuilds, reducing flicker.final ValueNotifier<bool> isLoading = ValueNotifier(true); class MyWidget extends StatelessWidget { @override Widget build(BuildContext context) { return ValueListenableBuilder<bool>( valueListenable: isLoading, builder: (context, loading, _) { return Scaffold( body: Center( child: loading ? CircularProgressIndicator() : Text('Loaded!'), ), ); }, ); } } // Update loading by changing isLoading.value = false;
2. Use
AnimatedSwitcherfor widget transitioningAnimatedSwitcherautomatically animates between two widgets fading or sliding without flicker.AnimatedSwitcher( duration: Duration(milliseconds: 300), child: isLoading ? CircularProgressIndicator(key: ValueKey('loading')) : Text('Loaded!', key: ValueKey('loaded')), )Make sure you provide keys, so Flutter knows they are distinct widgets to animate between.
3. Consider RepaintBoundary
Wrapping animated/frequently changing parts in a
RepaintBoundarywidget can contain costly repaints and reduce flicker caused by unnecessary redraw of other widgets.RepaintBoundary( child: CircularProgressIndicator(), )
4. Avoid rebuilding parent widgets unnecessarily
- Extract animation widgets into separate StatefulWidgets.
- If your animation is inside a large
buildmethod or parent widget, isolating it into its own widget can prevent parent rebuilds causing flicker.
E.g.:
class StableLoader extends StatefulWidget { @override _StableLoaderState createState() => _StableLoaderState(); } class _StableLoaderState extends State<StableLoader> { @override Widget build(BuildContext context) { return CircularProgressIndicator(); } }Then include
StableLoaderinside your page without rebuilding the entire page on state changes.
5. Use Flutter hooks (if you can use flutter_hooks)
flutter_hooksmakes it easy to manage animation controllers with lifecycle without verbose boilerplate:class MyHookWidget extends HookWidget { @override Widget build(BuildContext context) { final controller = useAnimationController(duration: Duration(seconds: 1)); final animation = ColorTween(begin: Colors.blue, end: Colors.red).animate(controller); useEffect(() { controller.repeat(reverse: true); return controller.dispose; }, [controller]); return AnimatedBuilder( animation: animation, builder: (_, __) => ElevatedButton( style: ElevatedButton.styleFrom(primary: animation.value), onPressed: () {}, child: Text('Animated'), ), ); } }This keeps animation controllers cleanly managed and prevents improper rebuilds.
6. Profile with Flutter DevTools
- Use Flutter Inspector and Performance tab to identify:
- How many rebuilds per second
- Jank caused by heavy widget rebuilds
- Repaints or layout thrashing
Fixing those often solves flickers.
7. Use GPU-accelerated animations & avoid expensive builds
- Prefer opacity, transform, and color animations over rebuilding widgets with complex layouts.
- Avoid changing widget trees deeply on each frame.
8. Use
FadeTransitioninstead of switching widgets suddenlyWhen replacing/loading widgets, fade between them to reduce flicker:
FadeTransition( opacity: _animationController, child: YourWidget(), )
Summary of alternative solutions:
Solution When to use Why ValueListenableBuilderFor simple UI state updates Partial rebuild, smooth UI AnimatedSwitcherFor switching between widgets Built-in fade/slide animation RepaintBoundaryExpensive widgets repaint optimization Limits repaint area Extract animations to sub-widgets Large UI with isolated animations Avoid full tree rebuild flicker flutter_hooksBetter controller lifecycle management Cleaner, less error-prone animations Profiling tools Diagnose rebuild/jank/flicker issues Find root cause Use GPU-friendly animations Opacity/transform instead of rebuilds Better performance
If you want I can:
- Provide an example using
AnimatedSwitcherorValueListenableBuilder - Help you refactor a problematic widget to be smooth
- Help you analyze a snippet of code that flickers
Feel free to share your code!
- User
Image.asset fit?
- Assistant
In Flutter, the
Image.assetwidget has afitproperty that controls how the image should be inscribed into the space allocated during layout. This property uses the BoxFit enum to specify how to fit the image within its container.
Common values of
BoxFitforfit:Value Description BoxFit.containScales the image to fit within the container while keeping aspect ratio (no cropping). BoxFit.coverScales the image to completely cover the container, may crop parts of the image (aspect ratio kept). BoxFit.fillStretch image to fill the container’s bounds (may distort aspect ratio). BoxFit.fitWidthScales image to match container width, height adjusts to maintain aspect ratio. BoxFit.fitHeightScales image to match container height, width adjusts to maintain aspect ratio. BoxFit.noneShows image at its natural size, no scaling. Image may be clipped if bigger than container. BoxFit.scaleDownSimilar to contain, but only scales down if image is larger than container, otherwise no scaling.
Example usage:
Image.asset( 'assets/images/sample.png', width: 200, height: 100, fit: BoxFit.cover, // Try contain, fill, fitWidth, etc. )
How
fitworks- If you don’t provide width/height constraints, the image takes its natural size.
- If width or height is fixed or constrained, the
fitdetermines how the image adjusts. - With nice aspect ratio preservation, use
BoxFit.containorBoxFit.cover.
Example with a container:
Container( width: 150, height: 150, color: Colors.grey[300], child: Image.asset( 'assets/images/sample.png', fit: BoxFit.contain, ), )This shows the image inside a 150x150 box, scaling it to fit inside while preserving aspect ratio.
Summary
- Use
fitto control how an asset image scales within its widget bounds. BoxFit.containkeeps the whole image visible.BoxFit.coverfills container fully but may crop.BoxFit.fillstretches image (may distort).- Choose based on desired UI effect.
Need an example of your use case or help fixing image layout? Just ask!