How can I implement AlertDialog box inside ListView in Flutter Android app automatically without pressing any button?

Issue

I am working on a project where I have created a RestApi where I have data of cars and which I keep updating every 3 sec. The cars are at a junction of 4 roads, now when a car is approaching towards a particular road denoted by id the "is_green" will become true and in the ListView -> the CircleAvtar will become green which will indicate that car is comming or not Now My Question is
how can I implement a AlertDialog box which will popup automically whithout pressing any button when bool isGreen = userData[index]["is_green"] will contain value true . I am new to flutter so I don’t know how to do that… Please help me out

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:async';
import 'dart:convert';

void main() {
  runApp(MaterialApp(
    debugShowCheckedModeBanner: false,
    theme: ThemeData.dark(),
    home: Home(),
  ));
}

class Home extends StatefulWidget {
  Home({Key key}) : super(key: key);
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  Map data;
  List userData;
  Future getData() async {
    print("updating data...");
    http.Response response = await http.get("http://10.100.101.154:3000/xd");
    data = jsonDecode(response.body);
    setState(() {
      userData = data["data"];
    });
  }

  @override
  void initState() {
    super.initState();

    Timer.periodic(new Duration(seconds: 3), (timer) {
      getData();
    });

  }

  Color getColor(bool isGreen) {
    if (isGreen == true) {
      return Colors.green;
    } else {
      return Colors.red;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('SGH'),
        centerTitle: true,
      ),
      body: ListView.builder(
          itemCount: userData == null ? 0 : userData.length,
          itemBuilder: (BuildContext context, int index) {
            bool isGreen = userData[index]["is_green"];
            return Card(
              child: Row(
                children: <Widget>[
                  Padding(
                    padding: EdgeInsets.all(10),
                    child: CircleAvatar(
                      backgroundColor: getColor(isGreen),
                      minRadius: 6,
                    ),
                  ),
                  Padding(
                    padding: EdgeInsets.all(10),
                    child: Wrap(
                      direction: Axis.horizontal,
                      children: <Widget>[
                        Text(
                          "Road Id = ${userData[index]["id"]} \CarInQueue = ${userData[index]["car_que"]} \nIsGreen ? --> ${userData[index]["is_green"]} ",
                          style: TextStyle(
                              fontSize: 20, fontWeight: FontWeight.bold),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            );
          }),
    );
  }
}

Solution

Just check any time you update list of cars… Then show a Dialog with informations about which car is crossing

Future getData() async {
    print("updating data...");
    http.Response response = await http.get("http://10.100.101.154:3000/xd");
    data = jsonDecode(response.body);
    setState(() {
      userData = data["data"];
    });
    checkDialog();
  }


checkDialog(){
var item = userData.where((car)=>car["is_green"]).first;//this is the first car where is_green is true
if(item!=null){
        showDialog(context:context,
        builder:(BuildContext context)=>AlertDialog( 
          //.... content here
         ));
}
}

Answered By – Constantin N.

Answer Checked By – Gilberto Lyons (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *