import 'package:build_with_ai/src/app_widget.dart' ;
import 'package:flutter/material.dart' ;
void main () {
runApp (const AppWidget ());
}
2 - Adicione o widget Principal
import 'package:flutter/material.dart' ;
import 'pages/home_page.dart' ;
class AppWidget extends StatelessWidget {
const AppWidget ({super .key});
@override
Widget build (BuildContext context) {
return MaterialApp (
home: const HomePage (),
);
}
}
import 'package:flutter/material.dart' ;
class HomePage extends StatefulWidget {
const HomePage ({super .key});
@override
State <HomePage > createState () => _HomePageState ();
}
class _HomePageState extends State <HomePage > {
@override
Widget build (BuildContext context) {
return Scaffold (
appBar: AppBar (
title: Text ('Chat App' ),
),
body: Column (
children: [],
),
);
}
}
4 - Adicione as Variaveis de controle
class _HomePageState extends State <HomePage > {
late final GenerativeModel gemini;
late ChatSession chatSession;
var initialized = false ;
var question = '' ;
var answer = '' ;
var isLoading = false ;
final txtController = TextEditingController ();
@override
Widget build (BuildContext context) {
(...)
}
}
class _HomePageState extends State <HomePage > {
(...)
@override
void initState () {
super .initState ();
gemini = GenerativeModel (
model: 'gemini-2.0-flash' ,
apiKey: 'API_KEY' ,
);
chatSession = gemini.startChat ();
initialized = true ;
setState ((){});
}
@override
Widget build (BuildContext context) {
(...)
}
}
6 - Criando Caixa de testo
@override
Widget build (BuildContext context) {
return Scaffold (
appBar: AppBar (
title: Text ('Chat App' ),
),
body: Column (
children: [
Padding (
padding: const EdgeInsets .all (8.0 ),
child: TextFormField (
controller: txtController,
onFieldSubmitted: (text) async {
setState (() {
question = text;
isLoading = true ;
});
txtController.clear ();
final response = await chatSession.sendMessage (Content .text (question));
setState (() {
answer = response.text ?? '' ;
isLoading = false ;
});
},
),
)
],
),
);
}
@override
import 'package:flutter/material.dart' ;
@override
Widget build (BuildContext context) {
return Scaffold (
appBar: AppBar (
title: Text ('Chat App' ),
),
body: Column (
children: [
if (! initialized)
CircularProgressIndicator ()
else
Expanded (
child: SingleChildScrollView (
child: Column (
children: [
Text (question),
Visibility (
visible: isLoading,
child: const CircularProgressIndicator (),
),
Visibility (
visible: ! isLoading,
child:
Align (alignment: Alignment .topLeft, child: Text (answer)),
),
Visibility (
visible: question.isEmpty && ! isLoading,
child: const Center (
child: Text ('Faça uma pergunta ao GEMINI!' ),
),
)
],
),
),
),
(...)
],
),
);
}
Melhorando