0

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(),) ;
      },
    ),

2 Answers 2

1

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>
    }
  }
)
0

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.

1
  • 1
    Thank you i use statefull widget and it ok Commented Jul 4, 2022 at 10:30

Not the answer you're looking for? Browse other questions tagged or ask your own question.