0

I am a bit stuck with writing code. I have two lists, one "listAll" with numbers of all computers and "listBusy", which I get from JSON, with numbers of busy computers.

I want to write code, which displayed in gridview icons (green color) of all computers, but if computer is busy, he will have different icon (red color).

Can someone help with understanding how to write right code?

Thanks for helping!

List<String> pcAll = [
  'S01',
  'S02',
  'S03',
  'S04',
  'S05',
  'S06',
  'S07',
  'S08',
  'S09',
  'S10',
  'S11',
  'S12',
  'S13',
  'S14',
  'S15',
  'S16',
  'S17',
  'S18',
  'S19'
];

List<String> pcBusy = [];

Future fetchDataStandart() async {
  final urlAuth =
      Uri.parse('http://XXX.XX.XXX.XXX/api/usersessions/activeinfo');
  final response = await http
      .get(urlAuth, headers: <String, String>{'authorization': basicAuth});

  if (response.statusCode == 200) {
    List listPc = List.from(json.decode(response.body)['result']);
    pcBusy.clear();
    for (int i = 0; i < listPc.length; i++) {
      return pcBusy.add(listPc[i]['hostName']);
    }
    print(pcBusy);
  } else {
    throw Exception('Error');
  }
}

Modified my code a little, not working

lass _EvrokoStandartScreenState extends State<EvrokoStandartScreen> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          centerTitle: true,
          title: Text(
            'ЕВРОКО Стандарт зал',
          ),
        ),
        body: FutureBuilder(
          future: getDataStandart(),
          builder: (context, AsyncSnapshot snapshot) {
            if (!snapshot.hasData) {
              return Center(
                child: CircularProgressIndicator(),
              );
            } else {
              return ComputerGrid();
            }
          },
        ));
  }
}

class ComputerGrid extends StatelessWidget {
  const ComputerGrid();

  @override
  Widget build(BuildContext context) {
    return GridView.builder(
      gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
        maxCrossAxisExtent: 200,
        childAspectRatio: 3 / 2,
        crossAxisSpacing: 20,
        mainAxisSpacing: 20,
      ),
      itemCount: pcAll.length,
      itemBuilder: (BuildContext context, index) {
        return GridTile(
          child: Container(
            color: pcBusy.contains(pcAll[index]) ? Colors.red : Colors.green,
            child: Text(
              pcBusy[index],
            ),
          ),
        );
      },
    );
  }
}

[![Error][1]][1]


  [1]: https://i.stack.imgur.com/keUZf.png
Чак Джонс
  • 115
  • 1
  • 1
  • 10

1 Answers1

0

Right, you have the right tools for this job. How I would do it, is as follows.

class ComputerGrid extends StatelessWidget {
  const ComputerGrid();

  @override
  Widget build(BuildContext context) {
    /// Assuming you store your lists and other logic in some state file
    return GridView.builder(
      /// Options to change the layout and look of your items.
      /// Play around with this a bit.
      gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
        maxCrossAxisExtent: 200,
        childAspectRatio: 3 / 2,
        crossAxisSpacing: 20,
        mainAxisSpacing: 20,
      ),

      /// You want as many items as there are entries in your listPc list
      itemCount: listPc.length,

      /// Building the actual items
      itemBuilder: (BuildContext context, index) {
        /// My example is barebones, play around with it to customize it
        return GridTile(
          child: Container(
            /// Change the color depending on whether the computer is in the busy list
            color: pcBusy.contains(listPc[index]['hostName'])
                ? Colors.red
                : Colors.green,
            child: Text(
              /// Show the number of the computer at the current index.
              listPc[index]['hostName'],
            ),
          ),
        );
      },
    );
  }
}

There's also a further optimization you can make in your for loop. You seem to have a background in JavaScript, and I think the for loop in Dart is much more elegant. The for loop below does the exact same as the one you have in your own code snippet.

    for (final pc in listPc) {
      pcBusy.add(pc['hostName']);
      continue;
    }
Tim Jacobs
  • 1,023
  • 1
  • 8
  • 14