Home > Software design >  How to call and API endpoint on initialize. Value is still null
How to call and API endpoint on initialize. Value is still null

Time:03-10

I am trying to get user information from an API. For this, I created a user object. I want to call the function and store it in a user. But the problem is, that I cannot use await and wait till all the data is there.

So instead of async and await, I tried to use .then and fill userInfo with the data. But now the email value is not showing. It is showing 'loading...'.

If I use Future I cannot do user.email.

Is it better to use FutureBuilder? Or try and use Async and Await (the call takes 2.5 seconds)

Here is the code

class Addressbook extends StatefulWidget {
  const Addressbook({Key? key}) : super(key: key);

  @override
  State<Addressbook> createState() => _AddressbookState();
}

class _AddressbookState extends State<Addressbook> {
  User? userInfo;
  Future<User> getUserInformation() async {
    User user = await UserService().getUserById(12345);
    return user;
  }

  @override
  void initState() {
    // TODO: implement initState
    getUserInformation().then((response) {
      userInfo = response;
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Mijn adresboek'),
        centerTitle: true,
        elevation: 0.5,
        titleTextStyle: const TextStyle(
          fontSize: 21,
          color: Colors.black,
          fontWeight: FontWeight.bold,
        ),
      ),
      body: Text(userInfo?.email ?? "loading..."),

    );
  }
}

What do I want to archive?

I want to display user data on the screen. In this case I want to show the email.

What is the problem?

User is not filled with data on init (probably because it is still loading to get the data).

My question

How can I solve this problem? Is async await a solution or should I use FutureBuilder? Can you give me a working sample?

Thanks for helping!

CodePudding user response:

You can use futurebuilder or you can use in initstate to fetch api

enter image description here

  @override
  void initState() {
    // TODO: implement initState
    Future.delayed(Duration(seconds: 10), () {
      setState(() {
        userinfo = "response";
      });
      // userinfo = "response";

    });
    super.initState();
  }

Inside the widget

Text(userinfo != null ? userinfo.toString() : "loading..."),

SAmple Code

import 'package:flutter/material.dart';
//import 'package:pucon/home.dart';

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

class MyApp extends StatefulWidget {
  MyApp({Key? key}) : super(key: key);

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

class _MyAppState extends State<MyApp> {
  String? userinfo = null;
  String? userinfo2 = null;

  @override
  void initState() {
    // TODO: implement initState
    Future.delayed(Duration(seconds: 10), () {
      setState(() {
        userinfo = "response";
      });
      // userinfo = "response";
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: ListView(
        shrinkWrap: true,
        children: [
          Text(""),
          Text(""),
          Text(userinfo != null ? userinfo.toString() : "loading..."),
          Row(
            children: [
              FutureBuilder(
                builder: (context, snapshot) {
                  if (snapshot.connectionState == ConnectionState.done) {
                    return Container(
                        child: Text(userinfo2.toString()), );
                  } else {
                    return SizedBox(
                      child: CircularProgressIndicator(),
                      height: 45,
                      width: 45,
                    );
                    // else
                    //   return Container(
                    //     child: CircularProgressIndicator(),
                    //     height: 45,
                    //     width: 45,
                    //   );
                  }
                },
                future: _future(),
              ),
            ],
          )
          // InsertData(),
        ],
      ),
    );
  }

  _future() async {
   await Future.delayed(Duration(seconds: 5), () {
     userinfo2 = "Completed";
      // setState(() {
      //
      // });
      // userinfo = "response";
    });
  }
}
  • Related