Search code examples
flutterdartflutter-http

How can I build a ListView with method variable in Widget. flutter/dart


I am trying to display a list from the method that I've made. I can print the message no problem but I want to display it as a list on the screen now. Forgive me as I am fairly new to dart but it seems that the error is that message isn't defined in the widget build.

This is my code :

enter image description here

import 'dart:convert';

import 'package:cache_manager/cache_manager.dart';
import 'package:flutter/material.dart';
import 'package:hong_leong_mockup_v6/request/response.dart';
import 'package:http/http.dart' as http;
import 'dart:io';

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

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

class _messageBoardState extends State<messageBoard> {
  
  getMessages() async {
    var newMessage = await (ReadCache.getString(key: 'cache1'));

    var response = await http.get(
      Uri.parse(
          'http://192.168.1.8:8080/HongLeong/MENU_REQUEST.do?_dc=1657717579436&table_id=25018&id_MenuAction=3&reset_context=1&ViewType=MENU_REQUEST&gui_open_popup=1&id_Window=5&activeWindowId=mw_5&noOrigUserDate=true&LocalDate=20220713&LocalTime=21061900&TimeZone=Asia/Shanghai&UserDate=0&UserTime=0&server_name=OPRISK_DATACOLLECTOR&key_id_list=&cell_context_id=0&id_Desktop=100237&operation_key=1000007&operation_sub_num=-1&is_json=1&is_popup=0&is_search_window=0&ccsfw_conf_by_user=0&is_batch=0&previousToken=1657717554097&historyToken=1657717579434&historyUrl=1'),
      headers: {HttpHeaders.cookieHeader: newMessage},
    );
    ResponseModel responseModel =
        ResponseModel.fromJson(jsonDecode(response.body));

    var message = responseModel.response.genericListAnswer.listNode
        .map((x) => x.toJson()['field'][0]['field_value'])
        .toList();

    print(message);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: Column(
        children: [
          ListView.builder(
              itemCount: message.length,
              itemBuilder: (context, index) {
                return Text(message[index]);
              }),
          Expanded(
            child: Center(
              child: TextButton(
                style: ButtonStyle(
                  foregroundColor:
                      MaterialStateProperty.all<Color>(Colors.blue),
                ),
                onPressed: getMessages,
                child: Text('TextButton'),
              ),
            ),
          )
        ],
      ),
    );
  }
}


Solution

  • You need to wrap your ListView.builder in a FutureBuilder because your list is built from an asynchronous request, which should be a future. If you want to do it the way you currently have it, it would not work because you'd need a public variable that will collect the data returned from the function and which would mean you'll need to await the function which is bad to do within your widget tree.

    You could share a code sample to get a more elaborate response.