I'm just trying to learn flutter and there's a piece of code in the flutter demo code, that you get when creating a new flutter project, that i don't understand :
title: new Text(widget.title)
I don't understand where widget comes from, as it is nowhere declared, defined or initialized. It refers to this Text:
home: new MyHomePage(title: 'Flutter Demo Home Page')
but why, has it something to do with context? And if its something predefined, how and where can i use it.
As everything in flutter is a Widget it's hard to ask Google for that problem.
import 'package:flutter/material.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: new Center(
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Text(
'You have pushed the button this many times:',
),
new Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
],
),
),
floatingActionButton: new FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: new Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
MyHomePage has final field title, which you declare in constructor - MyHomePage(title: 'Flutter Demo Home Page')``_MyHomePageState - it's a state of stateful widget. In every state you can use widget to get your StatefulWidget
Related
Good day everyone, Can someone help me with generating supabase user and password
what I want to achieve is to able import user csv to supabase auth.
for now Im able to generate user and password with navicat data generation but I cannot use that password because it's encrypted. does someone have a workaround for this
Generate user from navicat
Much better to write a custom application and create all users and disable email confirmation on the Supabase page.
I use Dart and Flutter, but you can do it on other languages as well:
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:supabase_flutter/supabase_flutter.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Supabase.initialize(
url: 'your_supabase_url',
anonKey:
'your_anon_key',
);
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.indigo,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Future<void> _createUsers() async {
final supabase = Supabase.instance.client;
for (var i = 0; i < 5; i++) {
final response =
await supabase.auth.signUp('test_$i#test.com', 'your_password');
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text(
'New app',
),
IconButton(onPressed: _createUsers, icon: const Icon(Icons.start)),
],
),
),
);
}
}
Just use a software like dbeaver to connect to supabase and to import your csv file from you local drive. Very easy.
You'll find your supabase database settings in the project settings menu.
I'm newbie, just how get variable value from this extends StatelessWidget in a flutter_deep_linking-master / multi level project using plugin URL launcher
how get the variable value of ${person.pdf} and insert it in String link = variable;
and put this new variable in onClicked: () => Utils.openLink(url: link),
class PersonPage extends StatelessWidget {
final Family family;
final Person person;
const PersonPage({required this.family, required this.person, Key? key}) : super(key: key);
#override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(title: Text(person.name)), body:
Text('\n\n' ' Le manuel recherché du ${family.name} ${person.name} est ici : \n\n'
' => **${person.pdf}** \n\n'));
}
//get the variable value of ${person.pdf} and insert it in : String link = => variable_value;
String link = variable_value;
class PersonPage extends StatelessWidget {
final Family family;
final Person person;
const PersonPage({required this.family, required this.person, Key? key}) : super(key: key);
#override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(title: Text(person.name)), body:
Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
buildButton(
text: 'Lien fichier pdf',
//put this new variable in : (url: link),
onClicked: () => Utils.openLink(url: =>link),
),
],
),
),
);
Widget buildButton({
required String text,
required VoidCallback onClicked,
}) =>
Container(
padding: const EdgeInsets.symmetric(vertical: 12),
child: ElevatedButton(
onPressed: onClicked,
child: Text(
text,
style: TextStyle(fontSize: 24),
),
),
);
}
class Four04Page extends StatelessWidget {
final String message;
const Four04Page({required this.message, Key? key}) : super(key: key);
#override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(title: const Text('Page Not Found')),
body: Center(child: Text(message)),
);
}
'thanks'
I've implemented this code to show a list of json data from a web url.
I've tried to implement a simple pull to refresh, but nothing works.
Flutter code is long, but it's pretty simple actually. It has main classes of flutter, and a future method to load json data from web.
I just want to implement a simple pull to refresh.
What am I missing here?
Why is it not working?
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:pull_to_refresh/pull_to_refresh.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'XXX',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'XXX'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final RefreshController _refreshController = RefreshController();
Future<List<User>> _getUsers() async {
var data = await http.get("xxxxxxxxxxxxx");
if (data.statusCode == 200) {
print('Status Code 200: Ok!');
var jsonData = json.decode(data.body);
List<User> users = [];
for (var k in jsonData.keys) {
var u = jsonData[k];
//print(u["pubdate"]);
User user = User(u["id"], u["source"], u["desc"], u["link"], u["title"], u["img"], u["pubdate"]);
users.add(user);
}
print(users.length);
return users;
} else {
throw Exception('Failed to load json');
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: SmartRefresher(
controller: _refreshController,
enablePullDown: true,
header: WaterDropHeader(),
onRefresh: () async {
await Future.delayed(Duration(seconds: 1));
_refreshController.refreshCompleted();
},
child: FutureBuilder(
future: _getUsers(),
builder: (BuildContext context, AsyncSnapshot snapshot){
if(snapshot.data == null){
return Container(
child: Center(
child: Text("Loading..."),
),
);
} else {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int id){
return ListTile(
leading: CircleAvatar(
backgroundImage: NetworkImage(
snapshot.data[id].img
),
),
title: Text(snapshot.data[id].title),
subtitle: Column(
children: <Widget>[
Row(
children: [
Text(
snapshot.data[id].source,
overflow: TextOverflow.fade,
maxLines: 1,
softWrap: false,
),
Spacer(),
Text(snapshot.data[id].pubdate),
],
),
],
)
);
},
);
}
},
),
),
);
}
}
class User {
final int id;
final String source;
final String desc;
final String link;
final String title;
final String img;
final String pubdate;
User(this.id, this.source, this.desc, this.link, this.title, this.img, this.pubdate);
}
Solved!
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:http/http.dart' as http;
import 'dart:convert';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'XXXX',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'XXXXXX'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
//Funcao para buscar as noticias
Future<List<User>> _getUsers() async {
var data = await http.get("XXXXX");
if (data.statusCode == 200) {
print('Status Code 200: Ok!');
var jsonData = json.decode(data.body);
List<User> users = [];
for (var k in jsonData.keys) {
var u = jsonData[k];
//print(u["pubdate"]);
User user = User(u["id"], u["source"], u["desc"], u["link"], u["title"], u["img"], u["pubdate"]);
users.add(user);
}
print(users.length);
return users;
} else {
throw Exception('Failed to load json');
}
}
var refreshKey = GlobalKey<RefreshIndicatorState>();
#override
void initState() {
super.initState();
refreshList();
}
Future<Null> refreshList() async {
refreshKey.currentState?.show(atTop: false);
await Future.delayed(Duration(seconds: 2));
setState(() {
_getUsers();
});
return null;
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: RefreshIndicator(
key: refreshKey,
child: FutureBuilder(
future: _getUsers(),
builder: (BuildContext context, AsyncSnapshot snapshot){
if(snapshot.data == null){
return Center(
child: CircularProgressIndicator(),
);
} else {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int id){
return ListTile(
leading: CircleAvatar(
backgroundImage: NetworkImage(
snapshot.data[id].img
),
),
title: Text(snapshot.data[id].title),
subtitle: Column(
children: <Widget>[
Row(
children: [
Text(
snapshot.data[id].source,
overflow: TextOverflow.fade,
maxLines: 1,
softWrap: false,
),
Spacer(),
Text(snapshot.data[id].pubdate),
],
),
],
)
);
},
);
}
},
),
onRefresh: refreshList,
),
);
}
}
class User {
final int id;
final String source;
final String desc;
final String link;
final String title;
final String img;
final String pubdate;
User(this.id, this.source, this.desc, this.link, this.title, this.img, this.pubdate);
}
You have to get users on onLoading as shown below
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: SmartRefresher(
....
onLoading: _getUsers,
.....
)
}
i have a class that call it in main class but i want pass a function to sub class and run function to sub class and return response of function to main class how to do in flutter dart.
Do
class subclassName
final function NameOfFunction;
subclassName(this.NameOfFunction);
in main class
subclassName(the function you want to pass);
main
class _MyAppState extends State<MyApp> {
var _questionIndex = 0;
void _answerQuestion() {
setState(() {
_questionIndex = _questionIndex + 1;
});
print(_questionIndex);
}
#override
Widget build(BuildContext context) {
print("object");
var questions = [
{
'questionText':'What\'s your favorite color?',
'answers': ['Black','Red','Green','White'],
},
{
'questionText':'What\'s your favorite animal?',
'answers': ['Rabbit','Snak','Elephant','Lion'],
},
{
'questionText':'who\'s your favorite instructor?',
'answers': ['suhaib','max','khalid','moh'],
}
];
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('My First App'),
),
body: Column(
children: [
Question(
questions[_questionIndex]['questionText'],
),
...(questions[_questionIndex]['answers'] as List<String>).map((answer){
return Answer(_answerQuestion, answer);
}).toList(),
],
),
),
);
}
}
sub class
class Answer extends StatelessWidget {
final String textanswer;
final Function answerQuestion;
Answer(this.answerQuestion,this.textanswer);
#override
Widget build(BuildContext context) {
return Container(
child: RaisedButton(
color: Colors.blue,
textColor: Colors.white,
child: Text(textanswer),
onPressed: answerQuestion,
),
);
}
}
In my flutter app. I am using google_maps_plugin . The link is https://github.com/flutter/plugins/tree/master/packages/google_maps_flutter .
I want to fix the marker in center of map without moving of icon after drag the map. I successfully done by using stack . But my question is how to get the longitude and latitude of icon I placed in stack .
I want it likes http://jsfiddle.net/UuDA6/
The code is shown below.
class MyApp extends StatelessWidget {
MyApp();
#override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Title',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new AppPage(title: 'Augr'),
);
}
}
class AppState extends InheritedWidget {
const AppState({
Key key,
this.mode,
Widget child,
}) : assert(mode != null),
assert(child != null),
super(key: key, child: child);
final Geocoding mode;
static AppState of(BuildContext context) {
return context.inheritFromWidgetOfExactType(AppState);
}
#override
bool updateShouldNotify(AppState old) => mode != old.mode;
}
class AppPage extends StatefulWidget{
AppPage() : super(key: key);
#override
_AppPageState createState() => new _AppPageState();
}
class _AppPagePageState extends State<MyApp> {
_AppPagePageState();
List<Address> results = [];
String address;
String googleMapsApiKey = 'APIKEY';
GoogleMapController mapController;
Position position;
#override
Widget build(BuildContext context){
return new Scaffold(
appBar: null,
body: Padding(
padding: EdgeInsets.only(top: 25.0),
child:Column(
children: <Widget>[
SizedBox(
width: 200,
height: 300,
child: Stack(
children: <Widget>[
GoogleMap(
onMapCreated: _onMapCreated,
),
InfoView()
],
),
),],
)
),
);
}
void initState() {
super.initState();
}
void _onMapCreated(GoogleMapController controller) {
setState(() {
mapController = controller;
mapController.animateCamera(CameraUpdate.newCameraPosition(
CameraPosition(
bearing: 270.0,
target: LatLng(lattitude, longitude),
tilt: 30.0,
zoom: 17.0,
),
));
});
}
}
class InfoView extends StatelessWidget {
const InfoView({
Key key,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return new Align(
alignment: Alignment.center,
child: new Icon(Icons.person_pin_circle, size: 40.0), //This the icon showing in google map .
);
}
}
The infoView() is defined the icon to show overlap in google map. I want to fetch the latitude and longitude of the icon place in map.
If any one have the idea about it please share it.