Home > Enterprise >  Snapshot data null but FutureBuilder return data?
Snapshot data null but FutureBuilder return data?

Time:06-29

I have http response data but IT IS NULL????? ...
Future getcategoryimage() async{ var url = "http://172.17.40.225/shoplacviet/getcategoryimage.php"; var reponse = await http.get(Uri.parse(url)); var list = reponse.body; Uint8List _bytesImage; _bytesImage = Base64Decoder().convert(list); return _bytesImage; }

...
FutureBuilder(
          future: getcategoryimage(),
          builder: (context,snapshot){
            List lista = snapshot.data as List;//------------> I have http response data but IT IS NULL?????
  if(snapshot.hasError) print(snapshot.error);
        return snapshot.hasData ? ListView.builder(
            scrollDirection: Axis.vertical,
            shrinkWrap: true,
            itemCount: lista.length,
            itemBuilder: (context,index){
              var blob = lista[index]['categoryimage'];
              Uint8List _bytesImage;
              _bytesImage = Base64Decoder().convert(blob);
              return Container(
                child: Image.memory(_bytesImage),
              );
            }):Center(child: CircularProgressIndicator(),) ;
      },
    ),

CodePudding user response:

You're building the future as the future: argument to your FutureBuilder. Since this is in a build() method, your future might be getting reset up to 60 times per second. The proper strategy (according to the first few paragraphs of the documentation) is:

The future must have been obtained earlier, e.g. during State.initState, State.didUpdateWidget, or State.didChangeDependencies. It must not be created during the State.build or StatelessWidget.build method call when constructing the FutureBuilder. If the future is created at the same time as the FutureBuilder, then every time the FutureBuilder's parent is rebuilt, the asynchronous task will be restarted. A general guideline is to assume that every build method could get called every frame, and to treat omitted calls as an optimization.

So there you have it. Move your call to getcategoryimage() out into initState(), saving it into a State variable.

I illustrate this in a 10-minute video, if you need further clarification.

CodePudding user response:

Do not access data before it is available. Use hasData and hasError properties something like this:

FutureBuilder<future type>(
  future: _future, // a previously-obtained Future
  builder: (BuildContext context, AsyncSnapshot<future type> snapshot) {
    if (snapshot.hasData) {
      // here snapshot.data is available
      return <hasData widget>
    } else if (snapshot.hasError) {
      return <hasError widget>
    } else {
      return <waiting widget>
    }
  }
)
  • Related