Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Flutter – "Expected a value of type 'Widget?', but got one of type 'String' "

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading