skip to Main Content

I’m having trouble displaying the result of api call in widget.
I’m getting "Unexpected null value" error.
From some reasons I don’t want to use FutureBuilder in this case. With FutureBuilder everything is ok.

class Album {
  final int userId;
  final int id;
  final String title;

  const Album({
    required this.userId,
    required this.id,
    required this.title,
  });

  factory Album.fromJson(Map<String, dynamic> json) {
    return Album(
      userId: json['userId'],
      id: json['id'],
      title: json['title'],
    );
  }
}

void main() => runApp(const MyApp());

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  Album ? myAlbum;
  Future<void>  fetchAlbum() async {
    final response = await http
        .get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1'));

    if (response.statusCode == 200) {
      // If the server did return a 200 OK response,
      // then parse the JSON.
      myAlbum= Album.fromJson(jsonDecode(response.body));
    } else {
      // If the server did not return a 200 OK response,
      // then throw an exception.
      throw Exception('Failed to load album');
    }
  }
  @override
  void initState() {
    fetchAlbum();
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Fetch Data Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Fetch Data Example'),
        ),
        body: Center(
          child: Text(myAlbum!.title)
        ),
      ),
    );
  }
}

I assume that problem is because widget is builded before initState call.

2

Answers


  1.             void initState() {
                 super.initState();
                  WidgetsBinding.instance
                 .addPostFrameCallback((_) => fetchAlbum());
                   }
    
    
       You can add this code in initState() So that api call will be executed 
       after WidgetBuilding.
    
    Login or Signup to reply.
  2. Have you checked API response ?
    It may be possibility that the value you are getting in response is null and you are trying to display it using widget.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search