Flutter报错Invalid argument(s): No host specified in URI排查求助
Hey there! That error pops up when Flutter tries to load a network image with a URL that's either incomplete, missing the required protocol (like http:///https://), or completely empty. Let's break down what's going wrong and how to fix it.
What's Causing the Error?
In your code, you're using Image.network(e['thumb_url']) directly with the value pulled from your videoList. The issue is almost certainly that some of the thumb_url values from your YouTube data aren't valid full URLs:
- They might be relative paths (like
/vi/abc123/thumb.jpginstead ofhttps://www.youtube.com/vi/abc123/thumb.jpg) - They could be missing the protocol (common with YouTube assets, e.g.,
//i.ytimg.com/vi/abc123/hqdefault.jpg) - Or, in some cases, the field might be empty or
nullentirely
How to Fix It
First, let's debug to confirm what URLs you're actually getting. Add a print statement inside your map function to check the thumb_url values:
videoList.map((e) { print('Thumb URL: ${e['thumb_url']}'); // Add this line to debug return GestureDetector( // ... rest of your code ); }).toList()
Once you know the pattern of the problematic URLs, you can add logic to clean them up before passing to Image.network():
Example Fixed Code
class _MyHomePageState extends State<MyHomePage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("Youtube list videos"), ), body: ListView( children: videoList.map((e) { // Clean up the thumbnail URL String thumbUrl = e['thumb_url'] ?? ''; if (thumbUrl.startsWith('//')) { // Add https protocol for URLs starting with // thumbUrl = 'https:$thumbUrl'; } else if (!thumbUrl.startsWith('http')) { // Handle relative paths or other incomplete URLs thumbUrl = 'https://www.youtube.com$thumbUrl'; } // Fallback to a placeholder if URL is still invalid/empty if (thumbUrl.isEmpty || !Uri.tryParse(thumbUrl)?.hasAbsolutePath ?? false) { thumbUrl = 'https://via.placeholder.com/150?text=No+Thumbnail'; } return GestureDetector( onTap: () => Navigator.push( context, MaterialPageRoute(builder: (context) => VideoScreen( name: e['name'], media_url: e['media_url'], )) ), child: Image.network(thumbUrl), ); }).toList(), ), ); } }
Bonus Tip
Don't forget to check the media_url you're passing to VideoScreen too! It's likely using the same data source, so it might have the same URL formatting issues. You can apply similar cleanup logic to it to avoid errors in the video screen.
内容的提问来源于stack exchange,提问作者Pimpi Rimpà

