How would I properly access the _runThisFunction(...) within the onTap()?
...
class _DealList extends State<DealList> with AutomaticKeepAliveClientMixin {
void _runThisFunction() async {
print('Run me')
}
#override
Widget build(BuildContext context) {
super.build(context);
return FutureBuilder(
future: _loadingDeals,
builder: (BuildContext context, AsyncSnapshot snapshot) {
return snapshot.connectionState == ConnectionState.done
? RefreshIndicator(
onRefresh: _handleRefresh,
child: ListView.builder(
physics: const AlwaysScrollableScrollPhysics(),
itemCount: snapshot.data['deals'].length,
itemBuilder: (context, index) {
final Map deal = snapshot.data['deals'][index];
return _getDealItem(deal, context);
},
),
)
: Center(
child: CircularProgressIndicator(),
);
},
);
}
}
Container _getDealItem(Map deal, context) {
return new Container(
height: 90.0,
child: Material(
child: InkWell(
child: _getDealRow(deal), // <-- this renders the row with the `deal` object
onTap: () {
// Below call fails
// 'The function isn't defined'
_runThisFunction();
},
),
),
);
}
The reason for that is that you are out of scope.
Little hint: The word "function" always indicates that the function you are trying to call is not part of a class and the keyword "method" shows you that the function you are trying to call is part of a class.
In your case, _runThisFunction is defined inside of _DealList, but you are trying to call it from outside.
You either need to move _getDealItem into _DealList or _runThisFunction out.
/// In this case both methods [_runThisFunction()] and [_getDealItem()] are defined inside [_DealList].
class _DealList extends State<DealList> with AutomaticKeepAliveClientMixin {
void _runThisFunction() ...
Container _getDealItem() ...
}
/// In this case both functions are defined globally.
void _runThisFunction() ...
Container _getDealItem() ...
You wil need to make sure that you also apply the same logic to _getDealRow and other nested calls.
Related
I am trying to use a StreamBuilder to fetch data and I want to display that data using a SliverList all inside a CustomScrollView so I can take advantage of the features that come with the CustomScrollView.
Any ideas on how I can achieve this?
Sure, it's easy, here you have a code sample:
class SampleStreamBuilder extends StatelessWidget {
Stream<List<String>> loadData() async* {
await Future.delayed(Duration(seconds: 3));
yield List.generate(10, (index) => "Index $index");
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: StreamBuilder<List<String>>(
stream: loadData(),
builder: (context, snapshot) {
return snapshot.hasData
? CustomScrollView(
slivers: [
SliverList(
delegate: SliverChildBuilderDelegate((context, index) {
return ListTile(
title: Text(snapshot.data[index]),
);
}, childCount: snapshot.data.length),
)
],
)
: Center(
child: CircularProgressIndicator(),
);
},
),
);
}
}
In this case it is fine to rerender the whole CustomScrollView. However if you want to rerender just one Sliver in a CustomScrollView, do it like this:
CustomScrollView(
slivers: <Widget>[
StreamBuilder(
stream: stream,
builder: (ctx, snapshot) {
return SliverToBoxAdapter(
child: Text('sliver box'),
);
},
)
],
),
Remember to always return a Sliver inside the StreamBuilder.
I'm discovering Flutter and the bloc pattern and to practice I'm making an app about pizzas.
I am using a BlocProvider to access the blocks. It is from the generic_bloc_provider package. It is a basic implementation using an InheritedWidget combined with a StatelessWidget.
I have a page with two editable textfields, for the name and price of the pizza I want to create. It is backed by a bloc.
Here's the code :
AddPizzaPage.dart :
class AddPizzaPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
print("Building AddPizzaPage");
return Scaffold(
appBar: AppBar(
title: Text("Adding Pizza"),
),
body: BlocProvider(
bloc: AddPizzaBloc(),
child: ModifyPizzaWidget(),
),
);
}
}
ListPage.dart:
class ModifyPizzaWidget extends StatelessWidget {
#override
Widget build(BuildContext context) {
final addPizzaBloc = BlocProvider.of<AddPizzaBloc>(context);
return Container(
margin: EdgeInsets.all(16.0),
child: Column(
children: <Widget>[
TextField(
decoration: InputDecoration(hintText: "Nom de la pizza"),
onChanged: (name) {
addPizzaBloc.pizzaNameSink.add(name);
},
),
TextField(
decoration: InputDecoration(hintText: "Prix de la pizza"),
keyboardType: TextInputType.number,
onChanged: (price) {
addPizzaBloc.pizzaPriceSink.add(price);
},
),
IconButton(
icon: Icon(Icons.check),
iconSize: 40,
onPressed: () {
addPizzaBloc.evenSink.add(AddPizzaEvent.VALIDATE);
Navigator.of(context).pop();
},
)
],
),
);
}
}
AddPizzaBloc.dart :
enum AddPizzaEvent {
VALIDATE
}
class AddPizzaBloc extends Bloc {
final _pizza = Pizza.empty();
final _pizzaSubject = BehaviorSubject<Pizza>();
final _repository = PizzaRepository();
Sink<String> get pizzaNameSink => _pizzaNameController.sink;
final _pizzaNameController = StreamController<String>();
Sink<String> get pizzaPriceSink => _pizzaPriceController.sink;
final _pizzaPriceController = StreamController<String>();
Sink<AddPizzaEvent> get evenSink => _eventSink.sink;
final _eventSink = StreamController<AddPizzaEvent>();
AddPizzaBloc() {
print("Created");
_pizzaNameController.stream.listen(_addPizzaName);
_pizzaPriceController.stream.listen(_addPizzaPrice);
_eventSink.stream.listen(_onEventReceived);
}
dispose() {
print("Disposed");
_pizzaSubject.close();
_pizzaNameController.close();
_pizzaPriceController.close();
_eventSink.close();
}
void _addPizzaName(String pizzaName) {
_pizza.name = pizzaName;
print(_pizza);
}
void _addPizzaPrice(String price) {
var pizzaPrice = double.tryParse(price) ?? 0.0;
_pizza.price = pizzaPrice;
print(_pizza);
}
void _onEventReceived(AddPizzaEvent event) {
print("Received $event");
if (event == AddPizzaEvent.VALIDATE) {
print(_pizza);
_repository.addPizza(_pizza);
}
}
}
My issue is that I store the Pizza being built inside the block but the widget is rebuilt, and so the bloc is rebuilt and I lose the state.
The full code is available on gitlab
I don't know how to use the bloc to power the addPizza form.
This happens because you're creating the instance of your BLoC within the build method:
BlocProvider(
bloc: Bloc(),
child: ...
)
The consequence is that any rebuild would not reuse the previous instance (with some awful memory leaks too).
The solution would be to make a StatefulWidget and create that BLoC instance within initState, followed by a dispose override to clean things.
But since you're using a package already, you can use provider instead. It is a popular alternative that does everything listed above.
As such your BlocProvider usage becomes:
StatefulProvider(
valueBuilder: (_) => AddPizzaBloc(),
dispose: (_, bloc) => bloc.dispose(),
child: // ...
),
then obtained as such:
Provider.of<AddPizzaBloc>(context);
I'm trying to change some variables in different methos in Flutter, but the value isn't changed.
An example is something like:
enum UserPlaceStatusType { NONE, GOING, THERE, OUT, CANCELLED }
class PlaceCardState extends State<PlaceCard> {
UserPlaceStatusType _isOtherPlaceActive = UserPlaceStatusType.NONE;
Widget build(BuildContext context) {
return Card(
child: Scaffold(
body: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: this._getBody(),
),
bottomNavigationBar: this._getBottomNavigationBar()));
}
List<Widget> _getBody() {
return [
Expanded(child: Text('test'), flex: 3),
Expanded(child: Text('test'), flex: 6),
Expanded(child: this._getActionsMenu(), flex: 1)
];
}
Widget _getActionsMenu() {
return Container(
padding: EdgeInsets.fromLTRB(0.0, 0.0, 10.0, 0.0),
child: IconButton(
icon: Icon(Icons.arrow_forward_ios),
color: Colors.grey[400],
onPressed: () {
showModalBottomSheet<void>(
context: context,
builder: (BuildContext context) {
return new Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
new ListTile(
leading: new Icon(Icons.train),
title: new Text(Utility.format(
Language.of(context).takePlace, [_place.title])),
onTap: () {
showUserStatusDialog<DialogActions>(
context: context,
//It opens a simple dialog
child: this._getCurrentUserPlaceStatus());
},
),
],
);
});
},
));
}
Widget _getCurrentUserPlaceStatus() {
return new GraphqlProvider(
client: new ValueNotifier(
Client(endPoint: 'GraphQLUrl', cache: new InMemoryCache()),
),
child: new Query(
'The GraphQL Query',
variables: {},
builder: ({
bool loading,
var data,
var error,
}) {
if (data != null && data['getCurrentUserPlaceStatus'] != null) {
this._isOtherPlaceActive = UserPlaceStatusType.THERE;
Navigator.pop(context, DialogActions.cancel);
return Container();
} else {
this._isOtherPlaceActive = UserPlaceStatusType.GOING;
Navigator.pop(context, DialogActions.cancel);
return Container();
}
},
));
}
void showUserStatusDialog<T>({BuildContext context, Widget child}) async {
//here there is a validation but the variable value is the initial one, I mean NONE
if (this._isOtherPlaceActive == UserPlaceStatusType.GOING) {
//Cod to do
return;
}
showDialog<T>(
context: context,
builder: (BuildContext context) => child,
).then<void>((T value) {
if (value != null) {
this._isOtherPlaceActive = UserPlaceStatusType.NONE;
Navigator.pop(context);
}
});
}
}
I changed the variable value through some methods, but when I need to apply the validation, that's the initial value, it isn't changed, and I could not apply SetState method cuz it breaks the modal and throws an exception.
I will appreciate any feedback.
The method setState() can't be called inside a widget directly. I'm curious with your use of GrapQLProvider since it returns an empty Container() widget just to check the status of the data.
While I'm unfamiliar with the use of GraphQL, if the client that you're using inherits either a Stream or Future, it can be used to listen when the query is done.
Here's some snippets as demo. Let _testFuture() as the sample for a Future callback.
Future _testFuture() async{
return null;
}
Future can be listened to inside a Widget. When the request finishes, we have the opportunity to call setState().
_testFuture().then((value) {
// Check for values here
setState(() {
// Update values
});
});
Or if the request is set in a Stream, it's also possible to listen for Stream changes inside a Widget.
_streamController.add(_testFuture());
_streamController.stream.listen((event) {
// Check for values here
setState(() {
// Update values
});
});
This may not be the exact answer that you're looking for, but I hope this can guide you for a solution to your approach. I also found a GraphQL sample that uses ObservableQuery as a Stream that you can try.
Your code is very complex and should be refactored. Please notice how dialogs must be called.
enum DialogResult {ok, cancel}
caller_widget.dart
FlatButton(
child: Text('Open dialog'),
onPressed: () async {
// Call dialog and wait for result (async call)
final dialogResult = await showDialog<DialogResult>(
context: context,
builder: (context) => DialogWidget(),
);
if (dialogResult == DialogResult.ok) {
// do something
}
},
),
dialog_widget.dart
...
FlatButton(
child: Text('Ok'),
onPressed: () => Navigator.pop(context, DialogResult.ok), // DialogResult.ok returns
),
FlatButton(
child: Text('Cancel'),
OnPressed: () => Navigator.pop(context, DialogResult.cancel), // DialogResult.cancel returns
),
So you can return required value from dialog and set it to required variable.
P.S. Try to avoid use of old fashion then process of futures and use async/await.
The issue:
I have 2 tabs using Default Tabs Controller, like so:
Widget build(BuildContext context) {
return DefaultTabController(
length: 2,
child: Scaffold(
drawer: Menu(),
appBar: AppBar(
title: Container(
child: Text('Dashboard'),
),
bottom: TabBar(
tabs: <Widget>[
Container(
padding: EdgeInsets.all(8.0),
child: Text('Deals'),
),
Container(
padding: EdgeInsets.all(8.0),
child: Text('Viewer'),
),
],
),
),
body: TabBarView(
children: <Widget>[
DealList(),
ViewersPage(),
],
),
),
);
}
}
The DealList() is a StatefulWidget which is built like this:
Widget build(BuildContext context) {
return FutureBuilder(
future: this.loadDeals(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
print('Has error: ${snapshot.hasError}');
print('Has data: ${snapshot.hasData}');
print('Snapshot data: ${snapshot.data}');
return snapshot.connectionState == ConnectionState.done
? RefreshIndicator(
onRefresh: showSomething,
child: ListView.builder(
physics: const AlwaysScrollableScrollPhysics(),
itemCount: snapshot.data['deals'].length,
itemBuilder: (context, index) {
final Map deal = snapshot.data['deals'][index];
print('A Deal: ${deal}');
return _getDealItem(deal, context);
},
),
)
: Center(
child: CircularProgressIndicator(),
);
},
);
}
}
With the above, here's what happens whenever I switch back to the DealList() tab: It reloads.
Is there a way to prevent re-run of the FutureBuilder when done once? (the plan is for user to use the RefreshIndicator to reload. So changing tabs should not trigger anything, unless explicitly done so by user.)
There are two issues here, the first:
When the TabController switches tabs, it unloads the old widget tree to save memory. If you want to change this behavior, you need to mixin AutomaticKeepAliveClientMixin to your tab widget's state.
class _DealListState extends State<DealList> with AutomaticKeepAliveClientMixin<DealList> {
#override
bool get wantKeepAlive => true;
#override
Widget build(BuildContext context) {
super.build(context); // need to call super method.
return /* ... */
}
}
The second issue is in your use of the FutureBuilder -
If you provide a new Future to a FutureBuilder, it can't tell that the results would be the same as the last time, so it has to rebuild. (Remember that Flutter may call your build method up to once a frame).
return FutureBuilder(
future: this.loadDeals(), // Creates a new future on every build invocation.
/* ... */
);
Instead, you want to assign the future to a member on your State class in initState, and then pass this value to the FutureBuilder. The ensures that the future is the same on subsequent rebuilds. If you want to force the State to reload the deals, you can always create a method which reassigns the _loadingDeals member and calls setState.
Future<...> _loadingDeals;
#override
void initState() {
_loadingDeals = loadDeals(); // only create the future once.
super.initState();
}
#override
Widget build(BuildContext context) {
super.build(context); // because we use the keep alive mixin.
return new FutureBuilder(future: _loadingDeals, /* ... */);
}
I am trying to navigate to a new page newData[index]["title"] when tap on listTile, how can I access newData, index and data variables out of this scope, I know I have to declare them in global scope but I tried this.index, but it doesn't work, I created a _onTap() method but I don't have access to index so I can only access the by asking for a specific position [0] for instance.
class _ContentPageState extends State<ContentPage> {
#override
Widget build(BuildContext context,) {
List data;
return new Scaffold(
appBar: new AppBar(
title: new Text("Local json file"),
),
body: new Container(
child: new Center(
child: new FutureBuilder(
future: DefaultAssetBundle
.of(context)
.loadString('data_files/file.json'),
builder: (context, snapshot) {
var newData = JSON.decode(snapshot.data.toString());
return new ListView.builder(
itemBuilder: (BuildContext context, int index) {
return new Card(
child: new ListTile(
title: new Text(newData[index]['title'],textScaleFactor: 1.5),
),
);
},
itemCount: newData == null ? 0 : newData.length,
);
}),
),
));
}
}
I guess you're trying to have a private _onTap method inside your class similar to :
_onTap(newData, int index) {
}
That's pretty simple, inside your ListTile you can wrap your _onTap inside another function like this :
return new Card(
child: new ListTile(
onTap: () => _onTap(newData, index),
title: new Text(newData[index]['title'], textScaleFactor: 1.5),
),
);
the previous answer is passing newData as argument. Another alternative is declare newData outside the build method.
class _ContentPageState extends State<ContentPage> {
var newData;// << here >> after class
#override
Widget build(BuildContext context,) {
So, in the assign remove de type (var)
newData = JSON.decode(snapshot.data.toString());