Async loading widget

  1. Summary of my problem
    Hi, I have the code below must perform the asynchronous loading of a rest call to a server, carried out by the method <Cantiere.Ricerca (…)> this method loads the values ​​and saves them within an array of objects, which can then be searched. To do this I use the code below, the problem lies in the fact that at the first view of the widget the results are not shown while clicking on a button on the menu and returning to the widget the result is shown, what is this error due to? I uploaded a video explaining the error, I also have another thing to correct the search bar returning to the widget is displayed twice, how come? how do i solve this?

Error Video: https://www.youtube.com/watch?v=tE3YazagO0E&feature=youtu.be

Flutter Code:

List listViews = [];
//Variabile che rappresenta l’utente all’interno della view
Utente utemp;
//Questa map rappresenta i cantieri ricercati
List cantieriricercati;

//La funzione di inizializzazione esegue l’init di tutti i valori che
//verranno utilizzati nella view
Future inizializzaValori(String testoricerca) async {
print(“Fase 1”);
//await Future.delayed(const Duration(milliseconds: 100));
// print(“sono all’interno della funzione che fa l’init dei valori”);
//Estrapolo i valori per inizializzare l’utente
var email = await Storage.leggi(“Email”);
var password = await Storage.leggi(“Password”);
var idutente = int.parse(await Storage.leggi(“IdUtente”));
//Inizializzo l’utente
utemp = new Utente.init(idutente, email, password);
//Inizializzo i cantieri all’avvio della form
cantieriricercati = await Cantiere.ricerca(utemp, 0, testoricerca, “”, false);
print("Cantiere caricati: " + cantieriricercati.length.toString());
return true;
}

class TrainingScreen extends StatefulWidget {
const TrainingScreen({Key key, this.animationController}) : super(key: key);

final AnimationController animationController;
@override
_TrainingScreenState createState() => _TrainingScreenState();
}

class _TrainingScreenState extends State
with TickerProviderStateMixin {
Animation topBarAnimation;

final ScrollController scrollController = ScrollController();
double topBarOpacity = 0.0;

@override
void initState() {
// You can’t use async/await here,
// We can’t mark this method as async because of the @override
inizializzaValori("").then((result) {
// If we need to rebuild the widget with the resulting data,
// make sure to use setState
setState(() {
new Future.delayed(const Duration(seconds: 2), () => “1”);
});
});
topBarAnimation = Tween(begin: 0.0, end: 1.0).animate(
CurvedAnimation(
parent: widget.animationController,
curve: Interval(0, 0.5, curve: Curves.fastOutSlowIn)));
addAllListData();

scrollController.addListener(() {
  if (scrollController.offset >= 24) {
    if (topBarOpacity != 1.0) {
      setState(() {
        topBarOpacity = 1.0;
      });
    }
  } else if (scrollController.offset <= 24 &&
      scrollController.offset >= 0) {
    if (topBarOpacity != scrollController.offset / 24) {
      setState(() {
        topBarOpacity = scrollController.offset / 24;
      });
    }
  } else if (scrollController.offset <= 0) {
    if (topBarOpacity != 0.0) {
      setState(() {
        topBarOpacity = 0.0;
      });
    }
  }
});
super.initState();

}

void addAllListData() {
const int count = 5;

listViews.add(
  new TextFormField(
    decoration: new InputDecoration(
      labelText: "Ricerca Cantieri",
      fillColor: Colors.white,
      border: new OutlineInputBorder(
        borderRadius: new BorderRadius.circular(25.0),
        borderSide: new BorderSide(),
      ),
      //fillColor: Colors.green
    ),
    validator: (val) {
      if (val.length == 0) {
        return "Il campo non può essere vuoto";
      } else {
        return null;
      }
    },
    keyboardType: TextInputType.emailAddress,
    style: new TextStyle(
      fontFamily: "WorkSansSemiBold",
    ),
  ),
);

//Aggiunta alla list della view corrispondente al cantiere
if (cantieriricercati != null) {
print(“Fase 3”);
//s print(“Cantieri ricercati non è null”);
//Eseguo la ricerca dei cantieri
for (int i = 0; i < cantieriricercati.length; i++)
{
print("\n Sono nel ciclo di for: " + i.toString());
//Aggiunta alla list della view corrispondente al cantiere
listViews.add(
SchedaCantieriView(
animation: Tween(begin: 0.0, end: 1.0).animate(
CurvedAnimation(
parent: widget.animationController,
curve: Interval((1 / count) * 2, 1.0,
curve: Curves.fastOutSlowIn))),
animationController: widget.animationController,
ctemp: cantieriricercati[i],
),
);
}
}
}

//Funzione che recupera i dati in modo asincrono
Future getData() async {
sleep(const Duration(seconds:3));
//await inizializzaValori("");
return true;
}

@override
Widget build(BuildContext context) {
return FutureBuilder(
future: getData(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if(snapshot.hasError) {
print(“Errore: lo snapshot presenta un errore”);
return Container();
} else {
return Container(
color: TemaApp.background,
child: Scaffold(
backgroundColor: Colors.transparent,
body: Stack(
children: [
getMainListViewUI(),
getAppBarUI(),
SizedBox(
height: MediaQuery.of(context).padding.bottom,
)
],
),
),
);
}

    });

}

Widget getMainListViewUI() {
return ListView.builder(
controller: scrollController,
padding: EdgeInsets.only(
top: AppBar().preferredSize.height +
MediaQuery.of(context).padding.top +
24,
bottom: 62 + MediaQuery.of(context).padding.bottom,
),
itemCount: listViews.length,
scrollDirection: Axis.vertical,
itemBuilder: (BuildContext context, int index) {
widget.animationController.forward();
return listViews[index];
},
);
}

Widget getAppBarUI() {
return Column(
children: [
AnimatedBuilder(
animation: widget.animationController,
builder: (BuildContext context, Widget child) {
return FadeTransition(
opacity: topBarAnimation,
child: Transform(
transform: Matrix4.translationValues(
0.0, 30 * (1.0 - topBarAnimation.value), 0.0),
child: Container(
decoration: BoxDecoration(
color: TemaApp.white.withOpacity(topBarOpacity),
borderRadius: const BorderRadius.only(
bottomLeft: Radius.circular(32.0),
),
boxShadow: [
BoxShadow(
color: TemaApp.grey.withOpacity(0.4 * topBarOpacity),
offset: const Offset(1.1, 1.1),
blurRadius: 10.0),
],
),
child: Column(
children: [
SizedBox(
height: MediaQuery.of(context).padding.top,
),
Padding(
padding: EdgeInsets.only(
left: 16,
right: 16,
top: 16 - 8.0 * topBarOpacity,
bottom: 12 - 8.0 * topBarOpacity),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Expanded(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
‘Cantieri’,
textAlign: TextAlign.left,
style: TextStyle(
fontFamily: TemaApp.fontName,
fontWeight: FontWeight.w700,
fontSize: 22 + 6 - 6 * topBarOpacity,
letterSpacing: 1.2,
color: TemaApp.darkerText,
),
),
),
),

                      ],
                    ),
                  )
                ],
              ),
            ),
          ),
        );
      },
    )
  ],
);

}
}

Hey @rikidev I request you to please post your code snippet again with formatting. You can do this by enclosing your code block in back ticks like this here . Please refer the default template that loads while posting a topic under Question/Help category.

String name;