Skip to content

Instantly share code, notes, and snippets.

@WilfredAlmeida
Last active March 20, 2023 16:42
Show Gist options
  • Save WilfredAlmeida/b3c409b754f927f218e00c2bb2eccf69 to your computer and use it in GitHub Desktop.
Save WilfredAlmeida/b3c409b754f927f218e00c2bb2eccf69 to your computer and use it in GitHub Desktop.
Flutter Hands-on Session

Flutter Hands-on Workshop

Who am I?

I am Wilfred, been developing using Flutter for a while now & trying to do better. Find me on my socials Portfolio, Twitter, LinkedIn

Flutter

Project

How to create one?

flutter create example

A look at the directories

Hands-on

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.

Moving out to files & folders

The Homepage

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

Rows & Columns

For building/placing other widgets on the screen the main widgets we can use

  1. Column - Places widgets in a vertical fashion

  2. 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;

//......

Making a new widget

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])

Now time to call API

Adding external dependency

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),
                          )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment