Deep linking: automatically push the route hiearchy on load. (#10894)
The main purpose of this PR is to make it so that when you set the initial route and it's a hierarchical route (e.g. `/a/b/c`), it implies multiple pushes, one for each step of the route (so in that case, `/`, `/a`, `/a/b`, and `/a/b/c`, in that order). If any of those routes don't exist, it falls back to '/'. As part of doing that, I: * Changed the default for MaterialApp.initialRoute to honor the actual initial route. * Added a MaterialApp.onUnknownRoute for handling bad routes. * Added a feature to flutter_driver that allows the host test script and the device test app to communicate. * Added a test to make sure `flutter drive --route` works. (Hopefully that will also prove `flutter run --route` works, though this isn't testing the `flutter` tool's side of that. My main concern is over whether the engine side works.) * Fixed `flutter drive` to output the right target file name. * Changed how the stocks app represents its data, so that we can show a page for a stock before we know if it exists. * Made it possible to show a stock page that doesn't exist. It shows a progress indicator if we're loading the data, or else shows a message saying it doesn't exist. * Changed the pathing structure of routes in stocks to work more sanely. * Made search in the stocks app actually work (before it only worked if we happened to accidentally trigger a rebuild). Added a test. * Replaced some custom code in the stocks app with a BackButton. * Added a "color" feature to BackButton to support the stocks use case. * Spaced out the ErrorWidget text a bit more. * Added `RouteSettings.copyWith`, which I ended up not using. * Improved the error messages around routing. While I was in some files I made a few formatting fixes, fixed some code health issues, and also removed `flaky: true` from some devicelab tests that have been stable for a while. Also added some documentation here and there.
This commit is contained in:
@@ -29,9 +29,7 @@ class StocksApp extends StatefulWidget {
|
||||
}
|
||||
|
||||
class StocksAppState extends State<StocksApp> {
|
||||
|
||||
final Map<String, Stock> _stocks = <String, Stock>{};
|
||||
final List<String> _symbols = <String>[];
|
||||
StockData stocks;
|
||||
|
||||
StockConfiguration _configuration = new StockConfiguration(
|
||||
stockMode: StockMode.optimistic,
|
||||
@@ -49,11 +47,7 @@ class StocksAppState extends State<StocksApp> {
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
new StockDataFetcher((StockData data) {
|
||||
setState(() {
|
||||
data.appendTo(_stocks, _symbols);
|
||||
});
|
||||
});
|
||||
stocks = new StockData();
|
||||
}
|
||||
|
||||
void configurationUpdater(StockConfiguration value) {
|
||||
@@ -80,19 +74,28 @@ class StocksAppState extends State<StocksApp> {
|
||||
}
|
||||
|
||||
Route<Null> _getRoute(RouteSettings settings) {
|
||||
// Routes, by convention, are split on slashes, like filesystem paths.
|
||||
final List<String> path = settings.name.split('/');
|
||||
// We only support paths that start with a slash, so bail if
|
||||
// the first component is not empty:
|
||||
if (path[0] != '')
|
||||
return null;
|
||||
if (path[1] == 'stock') {
|
||||
if (path.length != 3)
|
||||
// If the path is "/stock:..." then show a stock page for the
|
||||
// specified stock symbol.
|
||||
if (path[1].startsWith('stock:')) {
|
||||
// We don't yet support subpages of a stock, so bail if there's
|
||||
// any more path components.
|
||||
if (path.length != 2)
|
||||
return null;
|
||||
if (_stocks.containsKey(path[2])) {
|
||||
return new MaterialPageRoute<Null>(
|
||||
settings: settings,
|
||||
builder: (BuildContext context) => new StockSymbolPage(stock: _stocks[path[2]])
|
||||
);
|
||||
}
|
||||
// Extract the symbol part of "stock:..." and return a route
|
||||
// for that symbol.
|
||||
final String symbol = path[1].substring(6);
|
||||
return new MaterialPageRoute<Null>(
|
||||
settings: settings,
|
||||
builder: (BuildContext context) => new StockSymbolPage(symbol: symbol, stocks: stocks),
|
||||
);
|
||||
}
|
||||
// The other paths we support are in the routes table.
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -120,7 +123,7 @@ class StocksAppState extends State<StocksApp> {
|
||||
showPerformanceOverlay: _configuration.showPerformanceOverlay,
|
||||
showSemanticsDebugger: _configuration.showSemanticsDebugger,
|
||||
routes: <String, WidgetBuilder>{
|
||||
'/': (BuildContext context) => new StockHome(_stocks, _symbols, _configuration, configurationUpdater),
|
||||
'/': (BuildContext context) => new StockHome(stocks, _configuration, configurationUpdater),
|
||||
'/settings': (BuildContext context) => new StockSettings(_configuration, configurationUpdater)
|
||||
},
|
||||
onGenerateRoute: _getRoute,
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:math' as math;
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
|
||||
@@ -38,54 +39,64 @@ class Stock {
|
||||
}
|
||||
}
|
||||
|
||||
class StockData {
|
||||
StockData(this._data);
|
||||
|
||||
final List<List<String>> _data;
|
||||
|
||||
void appendTo(Map<String, Stock> stocks, List<String> symbols) {
|
||||
for (List<String> fields in _data) {
|
||||
final Stock stock = new Stock.fromFields(fields);
|
||||
symbols.add(stock.symbol);
|
||||
stocks[stock.symbol] = stock;
|
||||
class StockData extends ChangeNotifier {
|
||||
StockData() {
|
||||
if (actuallyFetchData) {
|
||||
_httpClient = createHttpClient();
|
||||
_fetchNextChunk();
|
||||
}
|
||||
symbols.sort();
|
||||
}
|
||||
}
|
||||
|
||||
typedef void StockDataCallback(StockData data);
|
||||
const int _kChunkCount = 30;
|
||||
|
||||
String _urlToFetch(int chunk) {
|
||||
return 'https://domokit.github.io/examples/stocks/data/stock_data_$chunk.json';
|
||||
}
|
||||
|
||||
class StockDataFetcher {
|
||||
StockDataFetcher(this.callback) {
|
||||
_httpClient = createHttpClient();
|
||||
_fetchNextChunk();
|
||||
}
|
||||
|
||||
final StockDataCallback callback;
|
||||
final List<String> _symbols = <String>[];
|
||||
final Map<String, Stock> _stocks = <String, Stock>{};
|
||||
|
||||
Iterable<String> get allSymbols => _symbols;
|
||||
|
||||
Stock operator [](String symbol) => _stocks[symbol];
|
||||
|
||||
bool get loading => _httpClient != null;
|
||||
|
||||
void add(List<List<String>> data) {
|
||||
for (List<String> fields in data) {
|
||||
final Stock stock = new Stock.fromFields(fields);
|
||||
_symbols.add(stock.symbol);
|
||||
_stocks[stock.symbol] = stock;
|
||||
}
|
||||
_symbols.sort();
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
static const int _kChunkCount = 30;
|
||||
int _nextChunk = 0;
|
||||
|
||||
String _urlToFetch(int chunk) {
|
||||
return 'https://domokit.github.io/examples/stocks/data/stock_data_$chunk.json';
|
||||
}
|
||||
|
||||
http.Client _httpClient;
|
||||
|
||||
static bool actuallyFetchData = true;
|
||||
|
||||
int _nextChunk = 0;
|
||||
|
||||
void _fetchNextChunk() {
|
||||
if (!actuallyFetchData)
|
||||
return;
|
||||
_httpClient.get(_urlToFetch(_nextChunk++)).then<Null>((http.Response response) {
|
||||
final String json = response.body;
|
||||
if (json == null) {
|
||||
print("Failed to load stock data chunk ${_nextChunk - 1}");
|
||||
return null;
|
||||
debugPrint('Failed to load stock data chunk ${_nextChunk - 1}');
|
||||
_end();
|
||||
return;
|
||||
}
|
||||
final JsonDecoder decoder = const JsonDecoder();
|
||||
callback(new StockData(decoder.convert(json)));
|
||||
if (_nextChunk < _kChunkCount)
|
||||
add(decoder.convert(json));
|
||||
if (_nextChunk < _kChunkCount) {
|
||||
_fetchNextChunk();
|
||||
} else {
|
||||
_end();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void _end() {
|
||||
_httpClient?.close();
|
||||
_httpClient = null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -50,10 +50,9 @@ class _NotImplementedDialog extends StatelessWidget {
|
||||
}
|
||||
|
||||
class StockHome extends StatefulWidget {
|
||||
const StockHome(this.stocks, this.symbols, this.configuration, this.updater);
|
||||
const StockHome(this.stocks, this.configuration, this.updater);
|
||||
|
||||
final Map<String, Stock> stocks;
|
||||
final List<String> symbols;
|
||||
final StockData stocks;
|
||||
final StockConfiguration configuration;
|
||||
final ValueChanged<StockConfiguration> updater;
|
||||
|
||||
@@ -62,10 +61,9 @@ class StockHome extends StatefulWidget {
|
||||
}
|
||||
|
||||
class StockHomeState extends State<StockHome> {
|
||||
|
||||
final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
|
||||
bool _isSearching = false;
|
||||
final TextEditingController _searchQuery = new TextEditingController();
|
||||
bool _isSearching = false;
|
||||
bool _autorefresh = false;
|
||||
|
||||
void _handleSearchBegin() {
|
||||
@@ -82,10 +80,6 @@ class StockHomeState extends State<StockHome> {
|
||||
});
|
||||
}
|
||||
|
||||
void _handleSearchEnd() {
|
||||
Navigator.pop(context);
|
||||
}
|
||||
|
||||
void _handleStockModeChange(StockMode value) {
|
||||
if (widget.updater != null)
|
||||
widget.updater(widget.configuration.copyWith(stockMode: value));
|
||||
@@ -233,8 +227,8 @@ class StockHomeState extends State<StockHome> {
|
||||
);
|
||||
}
|
||||
|
||||
Iterable<Stock> _getStockList(Iterable<String> symbols) {
|
||||
return symbols.map((String symbol) => widget.stocks[symbol])
|
||||
static Iterable<Stock> _getStockList(StockData stocks, Iterable<String> symbols) {
|
||||
return symbols.map<Stock>((String symbol) => stocks[symbol])
|
||||
.where((Stock stock) => stock != null);
|
||||
}
|
||||
|
||||
@@ -266,7 +260,7 @@ class StockHomeState extends State<StockHome> {
|
||||
stocks: stocks.toList(),
|
||||
onAction: _buyStock,
|
||||
onOpen: (Stock stock) {
|
||||
Navigator.pushNamed(context, '/stock/${stock.symbol}');
|
||||
Navigator.pushNamed(context, '/stock:${stock.symbol}');
|
||||
},
|
||||
onShow: (Stock stock) {
|
||||
_scaffoldKey.currentState.showBottomSheet<Null>((BuildContext context) => new StockSymbolBottomSheet(stock: stock));
|
||||
@@ -275,22 +269,21 @@ class StockHomeState extends State<StockHome> {
|
||||
}
|
||||
|
||||
Widget _buildStockTab(BuildContext context, StockHomeTab tab, List<String> stockSymbols) {
|
||||
return new Container(
|
||||
return new AnimatedBuilder(
|
||||
key: new ValueKey<StockHomeTab>(tab),
|
||||
child: _buildStockList(context, _filterBySearchQuery(_getStockList(stockSymbols)).toList(), tab),
|
||||
animation: new Listenable.merge(<Listenable>[_searchQuery, widget.stocks]),
|
||||
builder: (BuildContext context, Widget child) {
|
||||
return _buildStockList(context, _filterBySearchQuery(_getStockList(widget.stocks, stockSymbols)).toList(), tab);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
static const List<String> portfolioSymbols = const <String>["AAPL","FIZZ", "FIVE", "FLAT", "ZINC", "ZNGA"];
|
||||
|
||||
// TODO(abarth): Should we factor this into a SearchBar in the framework?
|
||||
Widget buildSearchBar() {
|
||||
return new AppBar(
|
||||
leading: new IconButton(
|
||||
icon: const Icon(Icons.arrow_back),
|
||||
leading: new BackButton(
|
||||
color: Theme.of(context).accentColor,
|
||||
onPressed: _handleSearchEnd,
|
||||
tooltip: 'Back',
|
||||
),
|
||||
title: new TextField(
|
||||
controller: _searchQuery,
|
||||
@@ -330,7 +323,7 @@ class StockHomeState extends State<StockHome> {
|
||||
drawer: _buildDrawer(context),
|
||||
body: new TabBarView(
|
||||
children: <Widget>[
|
||||
_buildStockTab(context, StockHomeTab.market, widget.symbols),
|
||||
_buildStockTab(context, StockHomeTab.market, widget.stocks.allSymbols),
|
||||
_buildStockTab(context, StockHomeTab.portfolio, portfolioSymbols),
|
||||
],
|
||||
),
|
||||
@@ -342,7 +335,6 @@ class StockHomeState extends State<StockHome> {
|
||||
class _CreateCompanySheet extends StatelessWidget {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
// TODO(ianh): Fill this out.
|
||||
return new Column(
|
||||
children: <Widget>[
|
||||
const TextField(
|
||||
@@ -351,6 +343,9 @@ class _CreateCompanySheet extends StatelessWidget {
|
||||
hintText: 'Company Name',
|
||||
),
|
||||
),
|
||||
const Text('(This demo is not yet complete.)'),
|
||||
// For example, we could add a button that actually updates the list
|
||||
// and then contacts the server, etc.
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ class _StockSymbolView extends StatelessWidget {
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
assert(stock != null);
|
||||
final String lastSale = "\$${stock.lastSale.toStringAsFixed(2)}";
|
||||
String changeInPrice = "${stock.percentChange.toStringAsFixed(2)}%";
|
||||
if (stock.percentChange > 0)
|
||||
@@ -63,30 +64,49 @@ class _StockSymbolView extends StatelessWidget {
|
||||
}
|
||||
|
||||
class StockSymbolPage extends StatelessWidget {
|
||||
const StockSymbolPage({ this.stock });
|
||||
const StockSymbolPage({ this.symbol, this.stocks });
|
||||
|
||||
final Stock stock;
|
||||
final String symbol;
|
||||
final StockData stocks;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return new Scaffold(
|
||||
appBar: new AppBar(
|
||||
title: new Text(stock.name)
|
||||
),
|
||||
body: new SingleChildScrollView(
|
||||
child: new Container(
|
||||
margin: const EdgeInsets.all(20.0),
|
||||
child: new Card(
|
||||
child: new _StockSymbolView(
|
||||
stock: stock,
|
||||
arrow: new Hero(
|
||||
tag: stock,
|
||||
child: new StockArrow(percentChange: stock.percentChange)
|
||||
return new AnimatedBuilder(
|
||||
animation: stocks,
|
||||
builder: (BuildContext context, Widget child) {
|
||||
final Stock stock = stocks[symbol];
|
||||
return new Scaffold(
|
||||
appBar: new AppBar(
|
||||
title: new Text(stock?.name ?? symbol)
|
||||
),
|
||||
body: new SingleChildScrollView(
|
||||
child: new Container(
|
||||
margin: const EdgeInsets.all(20.0),
|
||||
child: new Card(
|
||||
child: new AnimatedCrossFade(
|
||||
duration: const Duration(milliseconds: 300),
|
||||
firstChild: const Padding(
|
||||
padding: const EdgeInsets.all(20.0),
|
||||
child: const Center(child: const CircularProgressIndicator()),
|
||||
),
|
||||
secondChild: stock != null
|
||||
? new _StockSymbolView(
|
||||
stock: stock,
|
||||
arrow: new Hero(
|
||||
tag: stock,
|
||||
child: new StockArrow(percentChange: stock.percentChange),
|
||||
),
|
||||
) : new Padding(
|
||||
padding: const EdgeInsets.all(20.0),
|
||||
child: new Center(child: new Text('$symbol not found')),
|
||||
),
|
||||
crossFadeState: stock == null && stocks.loading ? CrossFadeState.showFirst : CrossFadeState.showSecond,
|
||||
),
|
||||
)
|
||||
)
|
||||
)
|
||||
)
|
||||
)
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,9 +46,9 @@ void checkIconColor(WidgetTester tester, String label, Color color) {
|
||||
}
|
||||
|
||||
void main() {
|
||||
stock_data.StockDataFetcher.actuallyFetchData = false;
|
||||
stock_data.StockData.actuallyFetchData = false;
|
||||
|
||||
testWidgets("Test icon colors", (WidgetTester tester) async {
|
||||
testWidgets('Icon colors', (WidgetTester tester) async {
|
||||
stocks.main(); // builds the app and schedules a frame but doesn't trigger one
|
||||
await tester.pump(); // see https://github.com/flutter/flutter/issues/1865
|
||||
await tester.pump(); // triggers a frame
|
||||
|
||||
@@ -7,14 +7,14 @@ import 'package:stocks/main.dart' as stocks;
|
||||
import 'package:stocks/stock_data.dart' as stock_data;
|
||||
|
||||
void main() {
|
||||
stock_data.StockDataFetcher.actuallyFetchData = false;
|
||||
stock_data.StockData.actuallyFetchData = false;
|
||||
|
||||
testWidgets("Test changing locale", (WidgetTester tester) async {
|
||||
testWidgets('Changing locale', (WidgetTester tester) async {
|
||||
stocks.main();
|
||||
await tester.idle(); // see https://github.com/flutter/flutter/issues/1865
|
||||
await tester.pump();
|
||||
expect(find.text('MARKET'), findsOneWidget);
|
||||
await tester.binding.setLocale("es", "US");
|
||||
await tester.binding.setLocale('es', 'US');
|
||||
await tester.idle();
|
||||
await tester.pump();
|
||||
expect(find.text('MERCADO'), findsOneWidget);
|
||||
|
||||
53
examples/stocks/test/search_test.dart
Normal file
53
examples/stocks/test/search_test.dart
Normal file
@@ -0,0 +1,53 @@
|
||||
// Copyright 2016 The Chromium Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:stocks/main.dart' as stocks;
|
||||
import 'package:stocks/stock_data.dart' as stock_data;
|
||||
|
||||
void main() {
|
||||
stock_data.StockData.actuallyFetchData = false;
|
||||
|
||||
testWidgets('Search', (WidgetTester tester) async {
|
||||
stocks.main(); // builds the app and schedules a frame but doesn't trigger one
|
||||
await tester.pump(); // see https://github.com/flutter/flutter/issues/1865
|
||||
await tester.pump(); // triggers a frame
|
||||
|
||||
expect(find.text('AAPL'), findsNothing);
|
||||
expect(find.text('BANA'), findsNothing);
|
||||
|
||||
final stocks.StocksAppState app = tester.state<stocks.StocksAppState>(find.byType(stocks.StocksApp));
|
||||
app.stocks.add(<List<String>>[
|
||||
// "Symbol","Name","LastSale","MarketCap","IPOyear","Sector","industry","Summary Quote"
|
||||
<String>['AAPL', 'Apple', '', '', '', '', '', ''],
|
||||
<String>['BANA', 'Banana', '', '', '', '', '', ''],
|
||||
]);
|
||||
await tester.pump();
|
||||
|
||||
expect(find.text('AAPL'), findsOneWidget);
|
||||
expect(find.text('BANA'), findsOneWidget);
|
||||
|
||||
await tester.tap(find.byTooltip('Search'));
|
||||
// We skip a minute at a time so that each phase of the animation
|
||||
// is done in two frames, the start frame and the end frame.
|
||||
// There are two phases currently, so that results in three frames.
|
||||
expect(await tester.pumpAndSettle(const Duration(minutes: 1)), 3);
|
||||
|
||||
expect(find.text('AAPL'), findsOneWidget);
|
||||
expect(find.text('BANA'), findsOneWidget);
|
||||
|
||||
await tester.enterText(find.byType(EditableText), 'B');
|
||||
await tester.pump();
|
||||
|
||||
expect(find.text('AAPL'), findsNothing);
|
||||
expect(find.text('BANA'), findsOneWidget);
|
||||
|
||||
await tester.enterText(find.byType(EditableText), 'X');
|
||||
await tester.pump();
|
||||
|
||||
expect(find.text('AAPL'), findsNothing);
|
||||
expect(find.text('BANA'), findsNothing);
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user