I am Wilfred, been developing using Flutter for a while now & trying to do better. Find me on my socials Portfolio, Twitter, LinkedIn
How to create one?
flutter create example
runApp
from the material
package will initialize your app and start building the tree
void main() async {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'ChatGPT Clone',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: HomeScreen(),
);
}
}
MaterialApp Who?
MaterialApp class is an application that uses material design. It is a convenience widget that wraps several widgets that are commonly required for material design applications.
class HomeScreen extends StatefulWidget {
const HomeScreen({Key? key}) : super(key: key);
@override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Chat GPT Clone"),
),
body: Center(
child: Text("Hello World")
));
}
}
Scaffold
acts as the base widget for a screen
appBar
displays an app bar on top of the scaffold
body
is the rest of the screen area in the scaffold
build
has the content displayed on the screen
For building/placing other widgets on the screen the main widgets we can use
-
Column - Places widgets in a vertical fashion
-
Row - Places widgets in a horizontal fashion
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Expanded(
child: historyWidgetsData.isEmpty
? const Center(
child: Text(
"No History Found",
textAlign: TextAlign.center,
),
)
: ListView.builder(
itemBuilder: (c, i) {
return Text("Placeholder");
},
itemCount: historyWidgetsData.length,
),
),
SizedBox(
height: 100,
child: Row(
children: [
SizedBox(
width: 350,
child: TextField(controller: controller),
),
_isLoading
? const CircularProgressIndicator()
: IconButton(
onPressed: {},
icon: const Icon(Icons.send),
)
],
),
)
],
),
)
Adding the missing variables
//......
class _HomeScreenState extends State<HomeScreen> {
List<Map<String, String>> historyWidgetsData = [];
TextEditingController controller = TextEditingController();
bool _isLoading = false;
//......
history_tile.dart
import 'package:flutter/material.dart';
class HistoryWidget extends StatelessWidget {
final String data;
const HistoryWidget({Key? key, required this.data}) : super(key: key);
@override
Widget build(BuildContext context) {
return Column(
children: [
ListTile(
title: Text(
data!,
textAlign: TextAlign.center,
overflow: TextOverflow.ellipsis,
),
onTap: () {
},
);
},
),
const Divider(
height: 2,
thickness: 2,
)
],
);
}
}
Stateless & Stateful Who?
Stateless Widget -> Doesn't Change
Stateful Widget -> Changes (Just like my ex)
Using this widget in homescreen
//....
return Text("Placeholder");
return HistoryWidget("Some Text")
//....
Adding some history data
List<String> historyWidgetsData = ["Monday", "Tuesday"];
return HistoryWidget(historyWidgetsData[i])
pubspec.yaml Who?
The pubspec file specifies dependencies that the project requires, such as particular packages (and their versions), fonts, or image files.
dependencies:
flutter:
sdk: flutter
http: ^0.13.5
Now calling the API
IconButton(
onPressed: () async {
String input = controller.text;
if (input.isEmpty) { ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text("Enter Some Input"),
),);
return;
}
setState(() {
_isLoading = true;
});
var uri = Uri.parse(
"https://api.openai.com/v1/completions");
var body = json.encode({
"model": "text-davinci-001",
"prompt": input,
"temperature": 0.6,
"max_tokens": 1000
});
var headers = {
'Authorization':
'Bearer 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',
'Content-Type': 'application/json'
};
var response = await http.post(uri,
body: body, headers: headers);
if (response.statusCode != 200) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text("Something went wrong"),
),
);
return;
}
var result = jsonDecode(response.body);
var resultText = result["choices"][0]['text'];
setState(() {
// historyWidgets.add(
// HistoryWidget(data: resultText));
historyWidgetsData.add(
{"title": input, "result": resultText});
_isLoading = false;
});
await FirebaseFirestore.instance
.collection("history")
.add({"title": input, "result": resultText});
},
icon: const Icon(Icons.send),
)