简体   繁体   中英

I'm getting this error "The operator '[]' isn't defined for the type 'Future<dynamic>'." can someone please help me fix my code? flutter/dart

I am getting these two errors when building a listview.

The getter 'length' isn't defined for the type 'Future'. The operator '[]' isn't defined for the type 'Future'.

whats going wrong here and is there any fix to my code.

Thanks Alot!

This is my code :

import 'package:cache_manager/cache_manager.dart';
import 'package:flutter/material.dart';



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

  @override
  State<messageBoard> createState() => _messageBoardState();
}

class _messageBoardState extends State<messageBoard> {

  @override
  Widget build(BuildContext context) {

      var message = ReadCache.getStringList(key: "cahce3");

      return Scaffold(
        backgroundColor: Colors.white,
        body: Column(
          children: [
            Expanded(
              child: FutureBuilder(
                builder: (context , snapshot) {
                  return ListView.builder(
                      itemCount: message.length,
                      itemBuilder:(context,index){
                        return Text(message[index]);
                      }
                  );
                },
              ),
            )],
        ),
      );
    }
  }

Future builder takes a future. You can assign the future to Futurebuilder and check its data. Assuming ReadCache.getStringList is a future you can write it like this.

FutureBuilder(
    future: ReadCache.getStringList(key: "cahce3"),
         builder: (context , snapshot) {
            if (snapshot.hasData) {     
                  return ListView.builder(
                      itemCount: snapshot.data.length,
                      itemBuilder:(context,index){
                        return Text(snapshot.data[index]);
                      }
                  );
                }
             else{ 
               return Text("No Data");
             }
          },
      ),

The ListView.builder still doesn't take a future. In your case it's probably built before the variable gets the values it's supposed to have.

Try putting var message = ReadCache.getStringList(key: "cahce3"); inside an initState() method.

Also you don't write logic inside the build() method. In a stateful widget build() gets called whenever something changes in the UI, basically all the time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM