0

I have a json file from where I am collecting only email addresses, and want to print index number base output like 3rd record's email address to Text widget..

class _HomeScreenState extends State<HomeScreen> {
  List<String> list = [];

  Future<List<String>> getcomments() async {
    Uri url =
        Uri.parse('https://jsonplaceholder.typicode.com/posts/1/comments');
    var response = await http.get(url);
    if (response.statusCode == 200) {
      var jsondata = json.decode(response.body);

      list.clear();
      for (var jdata in jsondata) {
        list.add(jdata['email']);
      }
    }
    return list;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('JSON'),
      ),
      body: Center(
        child: FutureBuilder(
          future: getcomments(),
          builder: (context, snapshot) {
            return Text(snapshot.data[2].toString());
            //here i want only 3rd data(index 2)
          },
        ),
      ),
    );
  }
}
2
  • can you post your result Commented Sep 5, 2022 at 13:23
  • showing an error Error: The operator '[]' isn't defined for the class 'Object?'. Commented Sep 5, 2022 at 13:24

1 Answer 1

1

Can you try this?

FutureBuilder(
      future: getcomments(),
      builder: (context, snapshot) {
        List<String> data = snapshot.data as List<String>;
        if (snapshot.connectionState == ConnectionState.waiting) {
          return const CircularProgressIndicator();
        }
        else {
          return Text(data[2]);
        }
      },
    ),
Sign up to request clarification or add additional context in comments.

2 Comments

also you should not forget the loading state when using futurebuilder
if I can use a statement like snapshot.data[index] inside a list view.builder, y it is not working with Text(snapshot.data[2])...this made me confused

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.