Home > Mobile >  Flutter - "Expected a value of type 'Widget?', but got one of type 'String'
Flutter - "Expected a value of type 'Widget?', but got one of type 'String'

Time:10-25

code output

Whenever I try fetching data from a REST API, I keep getting an error "Expected a value of type 'Widget?', but got one of type 'String'". There is nothing wrong with my code yet I keep getting the error.

This is the function for fetching items from the database.

Future<List<Map>> fetchItems() async {
    List<Map> items = [];

    //get data from API and assign to variable
    http.Response response =
        await http.get(Uri.parse("https://jsonplaceholder.typicode.com/posts"));

    if (response.statusCode == 200) {
      //get data from the response
      String jsonString = response.body;
      
      items = jsonDecode(jsonString).cast<Map>();
    }

    return items;
  }

This is my main.dart file

void main() {
  runApp(const MyApp());
}

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

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: PostList(),
    );
  }
}
class PostList extends StatelessWidget {
  PostList({super.key});

  final Future<List<Map>> _futurePosts = HTTPHelper().fetchItems();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Posts"),
      ),
      body: FutureBuilder(
        future: _futurePosts,
        builder: ((context, snapshot) {
          //check for error
          if (snapshot.hasError) {
            return Center(
                child: Text("Some error has occured ${snapshot.error}"));
          }
          //has data
          if (snapshot.hasData) {
            List<Map> _posts = snapshot.data!;
            return ListView.builder(
                itemCount: _posts.length,
                itemBuilder: ((context, index) {
                  Map _thisItem = _posts[index];
                  return ListTile(
                    title: _thisItem["title"],
                    subtitle: _thisItem["body"],
                  );
                }));
          }

          //display a loader
          return Center(child: CircularProgressIndicator());
        }),
      ),
    );

  }
}

Any solution to this error?

CodePudding user response:

The answer is pretty simple. You're assigning directly string value to the title(Which is expecting Widget). You can try below code

ListView.builder(
                itemCount: _posts.length,
                itemBuilder: ((context, index) {
                  Map _thisItem = _posts[index];
                  return ListTile(
                    title: Text(_thisItem["title"].toString()),
                    subtitle: Text(_thisItem["body"].toString()),
                  );
                }));

If this doesn't work. Please let me know.

CodePudding user response:

ListTile( title:NEED WIDGET HERE, subtitle:NEED WIDGET HERE,)

  • Related